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 Web 服务器中尝试过。
每个命令都在单独的 shell 中执行,因此第一个
cd
仅影响该 shell 进程,然后该进程终止。如果您想在特定目录中运行 git
,只需让 Node 为您设置路径即可:
exec('git status', {cwd: '/home/ubuntu/distro'}, /* ... */);
cwd
(当前工作目录)是 exec
的众多选项之一。
你的 shell 正在执行
cd
但只是每个 shell 在完成后都会丢弃它的工作目录。因此你又回到了第一个方向。
就您而言,您不需要多次调用 exec() 。您可以确保您的
cmd
变量包含多个指令,而不是 1 个。CD will 在这种情况下起作用。
var cmd = `ls
cd foo
ls`
var exec = require('child_process').exec;
exec(cmd, function(err, stdout, stderr) {
console.log(stdout);
})
注意:此代码应在 Linux 上运行,但不适用于 Windows。请参阅此处
它正在工作。但随后它就扔掉了外壳。节点为每个
exec
创建一个新的 shell。
以下选项可以提供帮助:http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
我正在使用它通过用户输入动态更改路径。
function changeDir(data, path) {
const dataStr = data.toString().toLowerCase();
path = path.replace(/\\/g, " ").split(" ");
if (dataStr.toLowerCase() === "exec cd ..") {
path.pop();
path = path.join("\\");
} else if (dataStr.indexOf("cd") === 5) {
if (dataStr.indexOf("to") === 8) return dataStr.split(" ").at(-1);
path.push(dataStr.split(" ").at(-1));
path = path.join("\\");
}
return path;
}