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 网络服务器中尝试过。
最佳答案
每个命令都在单独的 shell 中执行,因此第一个 cd
只会影响那个 shell 进程,然后该进程会终止。如果您想在特定目录中运行 git
,只需让 Node 为您设置路径即可:
exec('git status', {cwd: '/home/ubuntu/distro'}, /* ... */);
cwd
(当前工作目录)是 many options available for exec
之一.
关于javascript - nodeJS exec 不适用于 "cd "shell cmd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15629923/