Nodej 的 child_process 工作目录

我尝试 处决一个孩子处理在一个不同的目录然后其父目录之一。

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


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

我正在做以上的事情(当然,运行“ pwd”并不是我最终想要做的事情)。这将最终将父进程的 pwd 写入 stdout,而不管我为 cdw 选项提供了什么值。

我错过了什么?

(我确保作为 cwd 选项传递的路径确实存在)

73772 次浏览

The option is short for current working directory, and is spelled cwd, not 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. You can get around that by using the join function from the built-in Node.js path module. 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).

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