javascript - nodeJS exec 不适用于 "cd "shell cmd

标签 javascript node.js express exec

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/

相关文章:

node.js - Slack Node js程序运行 session 关闭

javascript - 路由时 express.js 不显示 console.log 消息

javascript - 单击表单中的链接,将文本区域传递给 php 文件进行处理后更新文本区域

database - Node : Batch insert of large number of rows into a database

javascript - npm 安装出错

javascript - 从中间件nodejs传递参数

javascript - 从 html 按钮执行 api 调用...如何

Javascript == 单值和数组之间的运算符

javascript - 如何在 Compromise.js 中匹配任何时态的动词

javascript - AJAX - 经典 ASP - 发布表单