Search code examples
node.jsmongodbseleniumspawn

How to spawn detached command in Node in silent/not_silent mode?


I'm making automation script for my node project and I've met little issue which I can not solve.

I want to start 3 detached proccesses using grunt tasks: selenium-standalone start for tests, mongod --dbpath ./mongo and node app.js. I use similar code for all of them

var spawn = require('child_process').spawn,
command = 'selenium-standalone.cmd', // or "mongod" or "node"
args = ['start']; // or ["--dbpath", path.join(process.cwd() + "/mongo/")] or ['app.js']
var ch = spawn(command, args, {
                detached: true,
                env: process.env,
                stdio: 'ignore'
            });
ch.unref();

All proccesses successfully start in background but with different behaviour. Selenium open new terminal window, so I can see what it does and I can close it by double ctrl+C. But mongod --dbpath ./mongo and node app.js is started silently. They works and I can find them in task manager (or by ps *mongod*).

So, my question: how can I affect this behaviour? I want to unify it and use some external config parameter to rule it.

I'm using node on Windows 10.

Thanks.


Solution

  • Workaround I found:

    // This one will close terminal window automatically.
    // all output will be in terminal window
    spawn("cmd", ["/k", "node", options.appFile], {
                        detached: true,
                        stdio: 'inherit'
                    }).unref(); 
    
    // This one will NOT close terminal window automatically after proccess ends his job
    // for some reason `spawn('start', [...])` will failed with ENOENT
    spawn("cmd", ["/c", "start", "cmd", '/k', "node", options.appFilePath], {
                    detached: true,
                    stdio: 'inherit'
                }).unref(); 
    
    // This is freak one. All output will go to the file. 
    // New terminal window will not be opened
    spawn("cmd", ["/c", "start", "cmd", '/k', "node", options.appFilePath, options.logFilePath,"2>&1"], {
                    detached: true,
                    stdio: 'inherit'
                }).unref();
    
    // This one is better than previous. Same result
    var out = fs.openSync(options.logFilePath, 'a'),
        stdioArgs = ['ignore', out, out];
    spawn("node", [options.appFilePath], {
                detached: true,
                stdio: stdioArgs
            }).unref(); 
    

    Hope, somebody will find it helpful.