It is not possible since the exec command starts a new process. But this is a link on a way to bypass the problem:
Is it possible to run an npm script in the current context using the source operator?
-
29-07-2023 - |
Question
I'm trying to write a simple Node.js CLI to more easily navigate directories. For the sake of simplicity, let's say this is the CLI I'm trying to make:
test.js
#!/usr/bin/env node
console.log('hey there');
var exec = require('child_process').exec;
exec('cd ~/code/');
package.json
{
"name": "example",
"version": "0.1.0",
"description": "Example CLI that needs to run in current context",
"bin": {
"myScript": "test.js"
},
"engines": {
"node": "0.10.*",
"npm": "1.2.*"
}
}
With both of those in the same folder, running npm link
will create the CLI. After that, if I run myScript
, it outputs "hey there" but doesn't change directories. I know that this is because myScript is run in it's own subshell, which is subsequently terminated. I've read here about the source operator and found that it's used like such:
. filename [arguments]
I've tried doing . myScript
to force my code to run in the current context. However, by using the source operator, the code is interpreted as bash instead of js. Here's the error I get:
-bash: /Users/dallinosmun/.nvm/v0.10.21/bin/myScript: line 3: syntax error near unexpected token `('
-bash: /Users/dallinosmun/.nvm/v0.10.21/bin/myScript: line 3: `var exec = require('child_process').exec;'
So, any ideas on how to get a Node.js CLI to run in the current context?
No correct solution
OTHER TIPS