nodeJS执行不工作的"cd "壳牌cmd

nodeJS exec does not work for "cd " shell cmd

本文关键字:quot cd 壳牌 cmd 执行 nodeJS 工作      更新时间:2023-09-26
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状态试图工作,但失败,因为它不是在git目录中执行,但CD CMD失败,阻止其他命令的进一步成功执行。在nodeJS shell以及nodeJS+ExpressJS webserver中尝试过

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

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

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

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

你的shell正在执行cd,但这只是每个shell在完成后扔掉它的工作目录。所以你又回到了起点。

在您的例子中,您不需要多次调用exec()。您可以确保您的cmd变量包含多条指令,而不是一条。CD 在这种情况下工作。
var cmd =  `ls
cd foo
ls`
var exec =  require('child_process').exec;
exec(cmd, function(err, stdout, stderr) {
        console.log(stdout);
})

注意:此代码应该在Linux上工作,但不能在Windows上工作。看到

正在工作。然后把壳扔掉。Node为每个exec创建一个新的shell。

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