I want to set/change user variable in my windows/Linux system. one of them is my APP_SOME_VAR variable.
When I run env in the command line I'm getting a list of my user variables.
When I run this code in my file.js it doesn't change my variable in the command line.
const { execSync } = require('child_process');
let output = execSync(`echo blabla && set APP_SOME_VAR=blabla`);
After I run the file, I do this in the command line:
node app.js
env | grep SOME
But I get nothing from: APP_SOME_VAR
How to do that with nodejs?
Related
Imagine this contrived scenario:
./main.sh
source ./config.sh
SOME_CONFIG="${SOME_CONFIG}bar"
./output.sh
./config.sh
export SOME_CONFIG='foo'
./output.sh
echo "Config is: ${SOME_CONFIG}"
I am trying to replace ./main.sh with a Node.js powered ./main.js WITHOUT replacing the other shell files. The exported ./config.sh functions/variables must also be fully available to ./output.sh
Here is a NON working ./main.js. I have written this for the sole purpose to explain what I want the final code to look like:
const terminal = require('child_process').spawn('bash')
terminal.stdin.write('source ./config.sh\n')
process.env.SOME_CONFIG = `${process.env.SOME_CONFIG}bar` // this must be done in JS
terminal.stdin.write('./output.sh\n') // this must be able to access all exported functions/variables in config.sh, including the JS modified SOME_CONFIG
How can I achieve this? Ideally if there's a library that can do this I'd prefer that.
While this doesn't fully answer my question, it solves the contrived problem I had at hand and could help others if need be.
In general, if bash scripts communicate with each other via environment variables (eg. using export/source), this will allow you to start moving bash code to Node.js.
./main.js
const child_process = require("child_process");
const os = require("os");
// Source config.sh and print the environment variables including SOME_CONFIG
const sourcedConfig = child_process
.execSync(". ./config.sh > /dev/null 2>&1 && env")
.toString();
// Convert ALL sourced environment variables into an object
const sourcedEnvVars = sourcedConfig
.split(os.EOL)
.map((line) => ({
env: `${line.substr(0, line.indexOf("="))}`,
val: `${line.substr(line.indexOf("=") + 1)}`,
}))
.reduce((envVarObject, envVarEntry) => {
envVarObject[envVarEntry.env] = envVarEntry.val;
return envVarObject;
}, {});
// Make changes
sourcedEnvVars["SOME_CONFIG"] = `${sourcedEnvVars["SOME_CONFIG"]}bar`;
// Run output.sh and pass in the environment variables we got from the previous command
child_process.execSync("./output.sh", {
env: sourcedEnvVars,
stdio: "inherit",
});
Is there anyway to make Nodejs continue to receive input like a general CLI when we called.
$ nodejs
For example: I have an index.js file below
// index.js
var a = 10
goToCLI()
What I expect is when I call $ nodejs ./index.js it will appear a nodejs cli with a variable already declared. Is it possible? If it is, how?
Start the Node.js REPL without your script first. Then, inside the REPL you may load your script.
$ node
> .load index.js
// index.js
var a = 10
undefined
> a
10
>
Alternatively, you can start up a REPLserver inside your script, along the lines of what your goToCLI() implied:
const repl = require('repl');
function initializeContext(context) {
// Initialize the REPL environment here.
// This is where your variable setup would go for instance:
context.a = 10;
}
const r = repl.start({ prompt: '> ' });
initializeContext(r.context);
r.on('reset', initializeContext);
Hope that helps!
You can use the REPL module. It will include any global variables in the scope, but others you need to add to the context. For example:
var repl = require("repl");
b = 20
repl.start("> ").context.a = 10
This will start the repl with both a and b in scope.
How to change or overwrite the variables of the default.json file of config module from cmd.
Here is the default.json file
"test":"TEST1"
and I want to change the test variable value from the cmd but when I run this command in cmd then I show the value of test which is set in default.json, not that value which I provide in cmd command.
Here is the command which I use for changing test value
$env:TEST="TEST_VALUE" node app.js
Please help me for solving this problem how can I do this from outside
You can do for Unix systems:
export test="Test1"
Use "set" for windows.
Hopefully this will help you...
default.json
{
"test":"TEST1"
}
app.js
DEFAULT_CONFIG = require('./default.json');
process.argv.forEach((arg,index)=>{
if(arg.match('--test')){
DEFAULT_CONFIG.test = process.argv[index+1] ?
process.argv[index+1] :
DEFAULT_CONFIG.test;
}
})
console.log(`test is now set to ${DEFAULT_CONFIG.test}`);
Command line
foo#bar:~$ node app.js
test is now set to TEST1
foo#bar:~$ node app.js --test TEST_VALUE
test is now set to TEST_VALUE
========================================================
Option #2
Based on the OP comment
default.json
{
"test":"TEST1"
}
dev_config.json
{
"test":"TEST_VALUE"
}
app.js
DEFAULT_CONFIG = process.env.NODE_ENV === 'dev' ?
require('./dev_config.json') :
require('./default.json');
Command line
To use dev_config.json config settings
foo#bar:~$ NODE_ENV=dev node app.js
or
To use regular default.json config settings
foo#bar:~$ node app.js
It seems like I can't access the $HOME property within my nodeJS app when running a child_process on my Linux machine:
var exec = require('child_process').exec
var testHome = `echo $HOME`
testHomeCmd = exec(testHome)
testHomeCmd.stdout.on('data', function (data) {
console.log(data)
})
Where the output I receive is: [17597]: /
If I run echo $HOME in terminal I receive:
$ echo $HOME
/home/cs4
Any thoughts?
I'm trying to pass a command line argument through node like so: npm start -s config.yml, where npm start maps to node app.js in my package.json.
app.js is as follows:
const program = require('commander');
console.log(process.argv);
program
.command('-s, --shell <value>', '.yml config file')
.parse(process.argv);
console.log(program.shell);
the argument is being passed through process.argv, but when I log program.shell it comes back undefined. What am I doing wrong?
Running the following:
$ node runme.js shell aceofspades
On the following file:
// FILE: runme.js
const program = require('commander');
program
.command('shell [value]', '.yml config file')
.action((cmd, opt) => {
console.log('cmd:', cmd); // shell
console.log('opt:', opt); // aceofspades
});
program.parse(process.argv);
Gives me the command and arguments within the action function for the command.