41
var sys = require('sys'),
    exec = require('child_process').exec;

exec("cd /home/ubuntu/distro", function(err, stdout, stderr) {
        console.log("cd: " + err + " : "  + stdout);
        exec("pwd", function(err, stdout, stderr) {
            console.log("pwd: " + err + " : " + stdout);
            exec("git status", function(err, stdout, stderr) {
                console.log("git status returned " ); console.log(err);
            })
        })
    })

cd: null :

pwd: null : /

git status returned 
{ [Error: Command failed: fatal: Not a git repository (or any of the parent directories): .git ] killed: false, code: 128, signal: null }

nodeJS exec 不适用于“cd”shell cmd。如下所示, pwd 有效, git status 正在尝试工作但失败,因为它没有在 git 目录中执行,但 cd cmd 无法阻止其他 cmd 的进一步成功执行。在 nodeJS shell 以及 nodeJS+ExpressJS 网络服务器中尝试过。

4

3 回答 3

78

Each command is executed in a separate shell, so the first cd only affects that shell process which then terminates. If you want to run git in a particular directory, just have Node set the path for you:

exec('git status', {cwd: '/home/ubuntu/distro'}, /* ... */);

cwd (current working directory) is one of many options available for exec.

于 2013-03-26T05:25:46.033 回答
6

而不是多次调用 exec() 。对多个命令调用一次 exec()

您的外壳正在执行cd,但只是每个外壳在完成后都会丢弃它的工作目录。因此,您又回到了第一方。

在您的情况下,您不需要多次调用 exec() 。您可以确保您的cmd变量包含多个指令而不是 1。CD在这种情况下可以工作。

var cmd =  `ls
cd foo
ls`

var exec =  require('child_process').exec;

exec(cmd, function(err, stdout, stderr) {
        console.log(stdout);
})

注意:此代码应该在Linux 上运行,但在 Windows 上不行。看这里

于 2017-05-25T03:07:07.927 回答
5

It is working. But then it is throwing the shell away. Node creates a new shell for each exec.

Here are options that can help: http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

于 2013-03-26T05:25:56.833 回答