Node child_process pass argv when forked - node.js

I have Node application with Express server. I also have node scripts in server folder. During some events I need get data from separate node scripts, so I create child process.
Without arguments, everything works fine, but I need to pass some data from parent process.
var express = require('express');
var router = express.Router();
var child_process = require('child_process');
router.get('/:site/start', function(req, res, next) {
const basedir = req.app.get('basedir');
const child_script_path = basedir + '/scripts/script.js';
const child_argv = [
'--slowmo=0',
'--headless=1'
];
child = child_process.fork(child_script_path, {
execArgv: child_argv
});
...
}
});
When I try to pass arguments and run script through Express, these errors are shown:
/home/user/.nvm/versions/node/v8.9.4/bin/node: bad option: --slowmo=0
/home/user/.nvm/versions/node/v8.9.4/bin/node: bad option: --headless=1
But when I run script from command line like :
node /scripts/script.js --slowmo=0 --headless=1
I get no errors and script can catch args from command line.
How can I pass args to child script in this situation?
Ubuntu 16.04
Node 8.9.4
Express 4.15.5

execArgv option is used to pass arguments for the execution process, not for your script.
This could be useful for passing specific execution environment to your forked process.
If you want to pass arguments to your script, you should use args.
child_process.fork(modulePath[, args][, options])
Example:
const child_process = require('child_process');
const child_script_path = './script.js';
const child_argv = [
'--foo',
'--bar'
]
const child_execArgv = [
'--use-strict'
]
let child = child_process.fork(child_script_path, child_argv, {
execArgv: child_execArgv // script.js will be executed in strict mode
})
// script.js
console.log(process.argv[2], process.argv[3]) // --foo --bar

Related

node.js child_process spawn repl

Nodejs Child Process: write to stdin from an already initialised process
I saw this link, so I try like this :
const { spawn } = require('child_process');
const child = spawn('node');
child.stdin.setDefaultEncoding('utf-8');
child.stdout.pipe(process.stdout);
child.stdin.cork();
child.stdin.write("10+20\n");
child.stdin.uncork();
but this code does not output anything, so what should I do?

Node How to share process.env between multiple runs?

Consider the following.
node file1.js && react-scripts start
I am trying to make an API call to the GCP Secret Manager in file1.js. After the request is received, I want to set them as environment variables under process.env. After that, I want to access them in the frontend. The browser can't make a call to that Secret Manager without OAuth. Is there any way I can share process.env between these two scripts?
File1 code
const {SecretManagerServiceClient} = require('#google-cloud/secret-manager');
// Instantiates a client
const client = new SecretManagerServiceClient();
const firebaseKeysResourceId = 'URL'
const getFireBaseKeys=async()=> {
const [version] = await client.accessSecretVersion({
name: firebaseKeysResourceId,
});
// Extract the payload as a string.
const payload = JSON.parse(version?.payload?.data?.toString() || '');
process.env.TEST= payload.TEST
return payload
}
getFireBaseKeys()
Expanding on my comment
Method 1 - kind of neat but unneccessary
Supposing you had these vars you wanted in the environment:
const passAlong = {
FOO: 'bar',
OAUTH: 'easy-crack',
N: 'eat'
}
Then at the end of file1.js you would do this
console.log(JSON.stringify(passAlong));
Note you cannot print anything else in file1.js
Then you would call your script like this
PASSALONG=$(node file1.js) react-script start
And at the beginning of react-script you would do this to populate the passed along variables into the environment.
const passAlong = JSON.parse(process.env.PASSALONG);
Object.assign(process.env,passAlong);
Method 2 - what I would do
Using the spawn method would involve just setting process.env how you like in file1.js and then adding something like this at the end of file1.js
// somewhere along the way
process.env.FOO = 'bar';
process.env.OAUTH = 'easy-crack';
process.env.N = 'eat';
// at the end of the script
require('child_process').spawnSync(
'node', // Calling a node script is really calling node
[ // with the script path as the first argument
'/path/to/react-script', // Using relative path will be relative
'start' // to where you call this from
],
{ stdio: 'inherit' }
);

How to execute the command NPM init in the nodejs file

How to execute the command npm init in the nodejs file? I want to use node. / index.js to execute the command. But what should I do if the command interacts with the user?
This code is directly stuck, and the subsequent question and answer cannot be carried out.I hope users can fill in the information normally
let exec = require('child_process').exec;
exec("npm init")
To allow users to fill in the questionnaire via the CLI, consider using the child_process module's spawn() method instead of exec().
*Nix (Linux, macOS, ... )
For example:
index.js
const spawn = require('child_process').spawn;
spawn('npm', ['init'], {
shell: true,
stdio: 'inherit'
});
Note: After the user has completed the questionnaire this example (above) creates the resultant package.json file in the current working directory, i.e. the same directory from where the node command invoked index.js.
However, If you want to ensure that package.json is always created in the same directory as where index.js resides then set the value of the cwd option to __dirname. For example:
const spawn = require('child_process').spawn;
spawn('npm', ['init'], {
cwd: __dirname, // <---
shell: true,
stdio: 'inherit'
});
Windows
If you are running node.js on Windows then you need to use the following variation instead:
script.js
const spawn = require('child_process').spawn;
spawn('cmd', ['/c', 'npm init'], { //<----
shell: true,
stdio: 'inherit'
});
This also utilizes the spawn() method, however it starts a new instance of Windows command shell (cmd). The /c option runs the npm init command and then terminates.
Cross-platform (Linux, macOS, Windows, ... )
For a cross platform solution, (i.e. one that runs on Windows, Linux, macOS), then consider combining the previous examples to produce the following variation:
script.js
const spawn = require('child_process').spawn;
const isWindows = process.platform === 'win32';
const cmd = isWindows ? 'cmd' : 'npm';
const args = isWindows ? ['/c', 'npm init'] : ['init'];
spawn(cmd, args, {
shell: true,
stdio: 'inherit'
});
Assuming there doesn't need to be any user input you could do:
let exec = require('child_process').exec;
exec("npm init -y")

How to make a child powershell process on node

I'm trying to have a spawned Powershell process on Windows with NodeJS, which i can send some commands, and the the output. I've did that with the stdio configuration form the parent node process, but i want to have it separated, and i cant achieve any of this to correctly work.
In this code, i was hoping to get the output of $PSTableVersion powershell variable on the psout.txt file, but it gets never written.
The simple code is:
var
express = require('express'),
fs = require('fs'),
spawn = require("child_process").spawn;
var err = fs.openSync('pserr.txt', 'w');
var out = fs.openSync('psout.txt', 'w');
var writer = fs.createWriteStream(null, {
fd: fs.openSync('psin.txt', 'w')
});
var child = spawn("powershell.exe", ["-Command", "-"], {
detached: true,
stdio: [writer, out, err]
});
writer.write('$PSTableVersion\n');
writer.end();
child.unref();
// just wait
var app = express();
app.listen(3000);
Update
I've tried with the code on this node github issue tracker: https://github.com/joyent/node/issues/8795
It seems calling .NET vs calling native executable are different things...

Spawn child_process on directory

How to spawn this command (/usr/bin/which flac) on node.js:
var spawn = require('child_process').spawn;
var cmd = spawn('/usr/bin/which flac', parameters);
I've tried that code but its not working, assuming that parameters variables are set.
In your case, flac needs to be passed as a parameter. Try this:
var spawn = require('child_process').spawn;
var cmd = spawn('/usr/bin/which', ['flac'], {detached:true, stdio: 'inherit'})
.on('exit',function(code){
//check exit code
});
For example, running the same code with node instead of flac gives:
/usr/bin/node

Resources