Change working directory in my current shell context when running Node script

前端 未结 4 1910
暖寄归人
暖寄归人 2021-01-31 00:49

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
proce         


        
4条回答
  •  庸人自扰
    2021-01-31 01:28

    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);
    }
    

    This is also testable in the Node.js REPL:

    [monitor@s2 ~]$ node
    > process.cwd()
    '/home/monitor'
    > process.chdir('../');
    undefined
    > process.cwd();
    '/home'
    

提交回复
热议问题