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

前端 未结 4 1907
暖寄归人
暖寄归人 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:16

    Short answer: no (easy?) way, but you can do something that serves your purpose.

    I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:

    spawn('bash', ['-i'], {
      cwd: new_cwd,
      env: new_env,
      stdio: 'inherit'
    });
    

    After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:

    • There is an additional process, so...
    • you have to write 'exit' to come back, and then...
    • after existing, all changes are undone.

    However, for me, that differences are desirable.

提交回复
热议问题