Spawn child_process on directory - node.js

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

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?

Execute bash script via Node.js and include command line parameters

I'm trying to execute a bash script from a Node application, which I have previously done successfully via:
var spawn = require('child_process').spawn;
spawn('bash', [pathToScript], {
stdio: 'ignore',
detached: true
}).unref();
It's important that I do it this way, because the script needs to continue to execute, even if/when the application is stopped.
Now, the script I need to execute requires an input value to be provided on the command line, ie.
./myScript.sh hello
But I cannot figure out how to pass this into the spawn call. I have tried the following, with no luck
var spawn = require('child_process').spawn;
spawn('bash', [pathToScript + '' + params], {
stdio: 'ignore',
detached: true
}).unref();
The second parameter in spawn is an array of arguments to pass to the command. So I think you almost have it but instead of concating the params to the path pass them in as an array:
var spawn = require('child_process').spawn;
var params = ['pathToScript','run', '-silent'];
spawn('bash', params, {
stdio: 'ignore',
detached: true
}).unref();

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")

node.js replace child_process.exec with spawn

this is my previous code:-
const child_process = require('child_process');
child_process.exec(`java -cp ./${dirPath}bin Main`);
I tried to replace this like below:-
let spawn = require('child_process').spawn;
let child = spawn('java', [`-cp ./${dirPath}bin Main`]);
but I got error :-
"options" argument must be an object
How can I use spawn to execute java file by giving a specific path?
This works without an error in Node 10 on Windows:
let spawn = require('child_process').spawn;
let child = spawn('java', ['-version']);
Of course, this code throws away all output.
Also, there is an error in arguments, so your code should look like
let spawn = require('child_process').spawn;
let child = spawn('java', ['-cp', `./${dirPath}bin`, 'Main']);
To Konstantin's answer --> please be aware, that child_process package contained malicious code and was removed from the registry by the npm security team.

Node child_process pass argv when forked

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

Resources