I'm taking a bigger-picture approach to show how processes can be managed using spawn(), etc.
I think you're making a fundamental error in that you're running this as a script to completion to start the process, and expecting to be able to run it again to stop the process. When the script stops the first time, ffmpegrec
no longer has any meaning; the JavaScript engine and all its global variables are disposed of. So on the second run, now you initialize ffmpegrec
to an empty string, just so it's some kind of Object
. This is voodoo coding.
Here's a demonstration script that stays alive so it can signal its child process after it has spawned it. You must find a way to keep the script running and somehow send it "start" and "stop" commands which then get relayed to the child ffmpeg process. This is a design challenge that's up to you. Then, you have to handle the child process with appropriate error and output listeners, you need to use functional abstraction, set all your variables in the right places, don't mix types, and check for errors. The following works. See if that straightens everything out for you.
var child_process = require('child_process');
var ffmpegrec = null;
function record(setting) {
if ( setting === 1 ) {
if ( ffmpegrec !== null ) {
console.log('Error! ffmpeg already running');
}
else {
// I don't have ffmeg installed, so simulating a long process instead
ffmpegrec = child_process.spawn('sh', ['-c', 'sleep 10']);
ffmpegrec.on('close', function(code, signal) {
console.log('child process terminated due to receipt of signal ' + signal + ' or code ' + code);
ffmpegrec = null;
});
ffmpegrec.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ffmpegrec.stderr.on('data', function (data) {
// important to monitor ffmegprec's complaints
console.log('stderr: ' + data);
});
// Can track using "ps" unix util, etc.
console.log('Initiated recording on PID ' + ffmpegrec.pid);
}
}
else if ( setting === 0 ) {
if ( ffmpegrec === null ) {
console.log('Error! Tried to stop recording and no recording active');
}
else {
ffmpegrec.kill('SIGINT');
// ffmpegrec will become null if and when signal delivery succeeds
console.log('Terminated recording');
}
}
else {
console.log('Error! Invalid value for setting: ' + setting);
}
}
console.log('Starting');
record(0); // Can't stop if not yet started; 1st error
record(1); // OK
record(1); // Can't start if already started; 2nd error
setTimeout(function() { record(0); /* OK to stop now */ }, 5000);