node.js replace child_process.exec with spawn - node.js

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.

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?

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 child_process.spawn not working with spaces in path on windows

How to provide a path to child_process.spawn
For example the path:
c:\users\marco\my documents\project\someexecutable
The path is provided by the enduser from a configuration file.
var child_process = require('child_process');
var path = require('path');
var pathToExecute = path.join(options.toolsPath, 'mspec.exe');
child_process.spawn(pathToExecute, options.args);
Currently only the part after the space is used by child_process.spawn
I also tried by adding quotes arround the path like this:
var child_process = require('child_process');
var path = require('path');
var pathToExecute = path.join(options.toolsPath, 'mspec.exe');
child_process.spawn('"' + pathToExecute + '"', options.args);
However this results in a ENOENT error.
The first parameter must be the command name, not the full path to the executable. There's an option called cwd to specify the working directory of the process, also you can make sure the executable is reachable adding it to your PATH variable (probably easier to do).
Also, the args array passed to spawn shouldn't contain empty elements.
You code should look something like this:
child_process.spawn('mspec.exe', options.args, {cwd: '...'});
As per https://github.com/nodejs/node/issues/7367#issuecomment-229728704 one can use the { shell: true } option.
For example
const { spawn } = require('child_process');
const ls = spawn(process.env.comspec, ['/c', 'dir /b "C:\\users\\Trevor\\Documents\\Adobe Scripts"'], { shell: true });
Will work.
I am using spawn frequently, the way I solved the problem is to use process.chdir. So if your path is c:\users\marco\my documents\project\someexecutable then you should do the following:
process.chdir('C:\\users\\marco\\my documents\\project');
child_process.spawn('./myBigFile.exe', options.args);
Note the double \s, that's how it worked for me.

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

Nodejs Child Process: write to stdin from an already initialised process

I am trying to spawn an external process phantomjs using node's child_process and then send information to that process after it was initialized, is that possible?
I have the following code:
var spawn = require('child_process').spawn,
child = spawn('phantomjs');
child.stdin.setEncoding = 'utf-8';
child.stdout.pipe(process.stdout);
child.stdin.write("console.log('Hello from PhantomJS')");
But the only thing I got on the stdout is the initial prompt for phantomjs console.
phantomjs>
So it seems the child.stdin.write is not making any effect.
I am not sure I can send additional information to phantomjs ater the initial spawn.
You need to pass also \n symbol to get your command work:
var spawn = require('child_process').spawn,
child = spawn('phantomjs');
child.stdin.setEncoding('utf-8');
child.stdout.pipe(process.stdout);
child.stdin.write("console.log('Hello from PhantomJS')\n");
child.stdin.end(); /// this call seems necessary, at least with plain node.js executable
You need to surround your write by cork and uncork, the uncork method flushes all data buffered since cork was called. child.stdin.end() will flush data too, but no more data accepted.
var spawn = require('child_process').spawn,
child = spawn('phantomjs');
child.stdin.setEncoding('utf-8');
child.stdout.pipe(process.stdout);
child.stdin.cork();
child.stdin.write("console.log('Hello from PhantomJS')\n");
child.stdin.uncork();

Resources