Bundling shell commands in NodeJs spawn

2019-08-06 04:13发布

问题:

I wish to run commands like NODE_ENV=production node server or cd ~/app/cms; npm test with NodeJs spawn

First can be achieved with

process.env.NODE_ENV = 'production'
start = spawn 'node', ['server'], process.env

But how can I achieve the second?

Updated: In case someone have similar problem, here is my example in coffeescript:

testCode = ->
    testCore = spawn 'npm', ['test']
    testCore.stderr.on 'data', (data) -> console.log() process.stderr.write data.toString()
    testCore.stdout.on 'data', (data) -> print data.toString()
    testCore.on 'exit', ->
        path = require 'path'
        process.chdir path.join(__dirname, "app", "linkParser")
        testModule = spawn 'npm', ['test']
        testModule.stderr.on 'data', (data) -> process.stderr.write data.toString()
        testModule.stdout.on 'data', (data) -> print data.toString()

回答1:

path = require "path"
process.chdir path.join(process.env.HOME, "app", "cms")
spawn "npm", "test"

http://nodejs.org/docs/latest/api/all.html#all_process_chdir_directory



回答2:

I received the ENOENT error while attempting to call cd from the child process.

@Peter Lyons answer was helpful. After reading more documentation on spawn, I decided to go with the following to keep the parent process working directory clean:

Coffeescript:

spawn "npm", "test",
  cwd: path.join(process.env.HOME, "app", "cms")

JavaScript:

spawn("npm", "test", { cwd: path.join(process.env.HOME, "app", "cms") });

By experience I found you can also pass just the string:

Coffeescript:

spawn "npm", "test", path.join(process.env.HOME, "app", "cms")

JavaScript:

spawn("npm", "test", path.join(process.env.HOME, "app", "cms"));

Check out spawn docs for more info.



标签: node.js shell