简体   繁体   English

NodeJs child_process 工作目录

[英]NodeJs child_process working directory

I am trying to execute a child process in a different directory then the one of its parent.我正在尝试在与其父进程不同的目录中执行子进程。

var exec = require('child_process').exec;

exec(
    'pwd',
    {
        cdw: someDirectoryVariable
    },
    function(error, stdout, stderr) {
        // ...
    }
);

I'm doing the above (though of course running "pwd" is not what I want to do in the end).我正在做上面的事情(当然,运行“pwd”并不是我最终想要做的)。 This will end up writing the pwd of the parent process to stdout, regardless of what value I provided to the cdw option.这最终会将父进程的密码写入标准输出,无论我为 cdw 选项提供什么值。

What am I missing?我错过了什么?

(I did make sure the path passed as cwd option actually exists) (我确实确保作为 cwd 选项传递的路径确实存在)

The option is short for current working directory , and is spelled cwd , not cdw . 该选项是当前工作目录的缩写,拼写为cwd ,而不是cdw

var exec = require('child_process').exec;
exec('pwd', {
  cwd: '/home/user/directory'
}, function(error, stdout, stderr) {
  // work with result
});

If you're on windows you might choke on the path separators.如果您使用的是 windows,您可能会被路径分隔符卡住。 You can get around that by using the join function from the built-in Node.js path module.您可以通过使用内置 Node.js path模块中的join function 来解决这个问题。 Here is @hexacyanide's answer but with execSync and join instead of exec (which doesn't block the event loop, but not always a huge deal for scripts) and Unix file paths (which are cooler and better than Window file paths).这是@hexacyanide 的答案,但使用execSyncjoin而不是exec (这不会阻止事件循环,但对于脚本来说并不总是很重要)和 Unix 文件路径(比 Window 文件路径更酷更好)。

const { execSync } = require('child_process');
const { join } = require('path');
exec('pwd', { cwd: path.join('home', 'user', 'directory') });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM