nodeJS exec不适用于"cd"shell cmd

use*_*121 27 javascript exec node.js express

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);
            })
        })
    })
Run Code Online (Sandbox Code Playgroud)
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 }
Run Code Online (Sandbox Code Playgroud)

nodeJS exec不适用于"cd"shell cmd.如下所示,pwd正常工作,git status正在尝试工作但失败,因为它没有在git目录中执行,但cd cmd无法停止进一步成功执行其他cmd.尝试在nodeJS shell以及nodeJS + ExpressJS webserver中.

ick*_*fay 52

每个命令都在一个单独的shell中执行,因此第一个命令cd只影响那个随后终止的shell进程.如果要git在特定目录中运行,只需让Node为您设置路径:

exec('git status', {cwd: '/home/ubuntu/distro'}, /* ... */);
Run Code Online (Sandbox Code Playgroud)

cwd(当前工作目录)是可用exec众多选项之一.


Fra*_*bot 6

这是工作。但随后它就扔掉了外壳。Node 为每个exec.

以下是可以提供帮助的选项:http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback


Cam*_*ron 5

而不是多次调用 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);
})
Run Code Online (Sandbox Code Playgroud)

注意:此代码应适用于Linux,但不适用于 Windows。看这里