bash 使用节点更改当前目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19563737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:24:01  来源:igfitidea点击:

Change current directory with node

javascriptnode.jsbashshell

提问by Hubert OG

I'm trying to write a command line utility in node.js. As one of the features it should change the current working directory of the shell it was called from. Something like node.js version of cd. Is it possible to achieve this? If so, how?

我正在尝试在 node.js 中编写一个命令行实用程序。作为功​​能之一,它应该更改调用它的 shell 的当前工作目录。类似于 node.js 版本的cd. 有可能实现这一目标吗?如果是这样,如何?

 

 



 

 

To clarify, I'd like to be able to change the current directory in the terminal window by running the script.

澄清一下,我希望能够通过运行脚本来更改终端窗口中的当前目录。

/some/path> ...
/some/path> nodecd /other/path
/other/path> ...

The problem is that process.chdir()works for the SCRIPT directory, not for the SHELL directory. I need to be able to somehow pass the current shell through the bash invocation to node script, and alter the path of that shell within the script - creating a subshell won't solve the problem.

问题是它process.chdir()适用于 SCRIPT 目录,而不适用于 SHELL 目录。我需要能够以某种方式通过 bash 调用将当前 shell 传递给节点脚本,并在脚本中更改该 shell 的路径 - 创建子 shell 不会解决问题。

回答by robertklep

In short: you can't. The working directory is limited to the context of a process (and perhaps child processes, but certainly not parent processes). So the cwd of your Node process cannot propagate back to your shell process.

简而言之:你不能。工作目录仅限于进程的上下文(可能还有子进程,但肯定不是父进程)。因此,您的 Node 进程的 cwd 无法传播回您的 shell 进程。

A common trick is to have your Node app print the working directory to stdout, and have your shell run your Node app like this:

一个常见的技巧是让你的 Node 应用程序将工作目录打印到标准输出,并让你的 shell 像这样运行你的 Node 应用程序:

cd "$(node app)"

A simple test case:

一个简单的测试用例:

// app.js
console.log('/tmp');

And if you create a shell alias/function for it, it should be relatively painless.

如果你为它创建一个 shell 别名/函数,它应该是相对轻松的。

回答by hek2mgl

To make it clear, you cannot change the pwd of the parent process. However you might change the working directory and start a shell in that folder.

明确地说,您不能更改父进程的密码。但是,您可能会更改工作目录并在该文件夹中启动 shell。



You need to use process.chdir():

你需要使用process.chdir()

console.log('Starting directory: ' + process.cwd());
try {
  process.chdir('/tmp');
  console.log('New directory: ' + process.cwd());
}
catch (err) {
  console.log('chdir: ' + err);
}

This example is taken from the manual. Here you can find the manual.

此示例取自手册。在这里您可以找到手册