运行Node脚本时,在当前shell上下文中更改工作目录 [英] Change working directory in my current shell context when running Node script
问题描述
我正在尝试从bin脚本运行时更改Node.js脚本的工作目录。我有以下内容:
I am trying to change the working directory of my Node.js script when it is run from a bin script. I have something like the following:
#!/usr/bin/env node
process.chdir('/Users')
当我用 ./ bin / nodefile运行此文件时
,它退出,但当前shell上下文的工作目录没有改变。我也尝试了 shelljs ,但这也不起作用。
When I then run this file with ./bin/nodefile
, it exits, but the working directory of the current shell context has not changed. I have also tried shelljs, but that does not work either.
做这个的最好方式是什么?我知道它正在运行,但它只是在一个单独的过程中。
What is the best way to do this? I understand it's working but it's just in a separate process.
推荐答案
更改目录的正确方法实际上是 process.chdir(目录)
。以下是文档中的示例:
The correct way to change directories is actually with process.chdir(directory)
. Here's an example from the documentation:
console.log('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
console.log('New directory: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
这在Node.js REPL中也是可测试的:
This is also testable in the Node.js REPL:
[monitor@s2 ~]$ node
> process.cwd()
'/home/monitor'
> process.chdir('../');
undefined
> process.cwd();
'/home'
这篇关于运行Node脚本时,在当前shell上下文中更改工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!