how to set temporary JDK Path using nodeJs child-process module - node.js

I am taking the JDK path from user input and want to set that path as temporary path using nodeJS spawn, so that I can use that temporary path in my .bat file from session.
I am doing this to run my .bat file with dynamic JDK path:
child_process=require('child_process')
const child = child_process.spawn('cmd.exe', ['/c', 'set PATH=D:\\jdk-18.0.1.1\\bin']);
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});

Related

How to make spawned process know it's not writing to a terminal (nodejs)

I'm writing a little wrapper to the lzma command in Linux but the program refuses to write to stdout because it believes to be in an interactive terminal:
lzma: Compressed data cannot be written to a terminal
This is my code in js
// Compress a given string using the lzma program, and return the compressed contents.
const { spawn } = require('child_process')
const compress = str => new Promise((resolve, reject) => {
const lzma = spawn('lzma', ["-z", "-c", "-9"],
{ stdio: [process.stdin, process.stdout, process.stderr] })
lzma.on('error', err => {
// console.log(`Failed to start lzma: ${err}`)
reject(err)
})
lzma.on('exit', (code, signal) => {
if (code) {
// console.log(`lzma process exited with code ${code}`)
reject(code)
}
else if (signal) {
// console.log(`lzma process exited with signal ${signal}`)
reject(signal)
}
else {
// console.log(`lzma process exited successfully`)
resolve(compressed)
}
})
lzma.stdin.write(str)
lzma.stdin.end()
let compressed = ''
lzma.stdout.on('data', data => { compressed += data })
})
module.exports = compress
How do I override this behavior?
Try changing line 9 to:
{ stdio: ["pipe", "pipe", "inherit"] })
lzma.stdin and lzma.stdout won't do anything unless they're connected to a pipe. "inherit" means that if lzma writes to stderr, you'll see it on the calling process's stderr.
See the node docs for more info.

Node.js child_process STDOUT not showing progressbar

I've a problem with displaying the progressbar of a process executed by child_process spawn in a discord bot.
CLI Output:
2021-09-16 16:11:03 Welcome to Minecraft Overviewer version 0.17.39 (2402e41)!
2021-09-16 16:11:03 Generating textures...
2021-09-16 16:12:52 Preprocessing...
2021-09-16 16:15:14 Rendering 228498 total tiles.
99% [===================================================================================================================================================================================================== ] 228494 17.65t/s eta 00h 00m 00s
2021-09-16 19:50:57 Rendering complete!
When using the child_process spawn I get every output except for the progressbar.
Node script:
const child_process = require('child_process');
const command = "python";
const arguments = ["./Minecraft-Overviewer/overviewer.py", "--config=./world.py"]
var child = child_process.spawn(command, arguments, {
encoding: 'utf8',
shell: true
});
child.on('error', (error) => {
message.channel.send('Error!\r\n' + error);
});
child.stdout.setEncoding('utf8');
child.stdout.on('data', (data) => {
data = data.toString();
message.channel.send(`STDOUT: ${data}`);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
message.channel.send(`DATA: ${data}`);
});
child.on('close', (code) => {
//Here you can get the exit code of the script
switch (code) {
case 0:
message.channel.send('Process exited.');
break;
}
});
Any ideas on how I can catch the progressbar as well?
Many thanks in advance!

Execute bat file using node js

I have written code to execute bat file using nodejs, but it is restricting me to place the bat file at the same location where package.json file is present and it is not accepting absolute path.
I am using the following code:
const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c','coma.bat']);
bat.stdout.on('data', (data) => {
console.log('data is : '+data.toString());
});
bat.stderr.on('data', (data) => {
console.error('error is : '+data.toString());
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
it accepts full path (if this is the question):
const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c','C:\\scripts\\somescript.bat']);

Node.js Child process can not catch windows exe file's output

I want to use child_process.spawn to execute a windows exe file and catch it's output.
When I use command line to run a thirdparty exe file (says A.exe), it will print some logs to the cmd window. Like this:
C:\> A.exe
some outputs...
some more outputs...
However, when I spawn it in node.js, using this
import childProcess from 'child_process';
const cp = childProcess.spawn('A.exe');
cp.stdout.on('data', data => console.log(`stdout: ${data}`));
cp.stderr.on('data', data => console.log(`stderr: ${data}`));
There is no outputs at all.
I think the outputs of A.exe is not to the stdout (so I can never get data by listening stdout), but I don't know how it print logs when running from command line.
Any help would be greatly appreciated.
On Unix-type operating systems (Unix, Linux, macOS) child_process.execFile() can be more efficient because it does not spawn a shell. On Windows, however, .bat and .cmd files are not executable on their own without a terminal, and therefore cannot be launched using child_process.execFile(). When running on Windows, .bat and .cmd files can be invoked using child_process.spawn() with the shell option set, with child_process.exec(), or by spawning cmd.exe and passing the .bat or .cmd file as an argument (which is what the shell option and child_process.exec() do). In any case, if the script filename contains spaces it needs to be quoted.
// On Windows Only ...
const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
bat.stdout.on('data', (data) => {
console.log(data.toString());
});
bat.stderr.on('data', (data) => {
console.log(data.toString());
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
Maybe give this approach a go:
var childProcess = require('child_process');
childProcess.exec('A.exe', function(error, stdout, stderr) {
if (error != null) {
console.log('error occurred: ' + error);
} else {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
}
});
// OR
var cp = childProcess.spawn('A.exe');
cp.stdout.on('data', (data) => {
console.log('stdout: ' + data.toString());
});
cp.stderr.on('data', (data) => {
console.log('stderr: ' + data.toString());
});

Exec : display stdout "live"

I have this simple script :
var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee', function(error, stdout, stderr) {
console.log(stdout);
});
where I simply execute a command to compile a coffee-script file. But stdout never get displayed in the console, because the command never ends (because of the -w option of coffee).
If I execute the command directly from the console I get message like this :
18:05:59 - compiled my_file.coffee
My question is : is it possible to display these messages with the node.js exec ? If yes how ? !
Thanks
Don't use exec. Use spawn which is an EventEmmiter object. Then you can listen to stdout/stderr events (spawn.stdout.on('data',callback..)) as they happen.
From NodeJS documentation:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code.toString());
});
exec buffers the output and usually returns it when the command has finished executing.
exec will also return a ChildProcess object that is an EventEmitter.
var exec = require('child_process').exec;
var coffeeProcess = exec('coffee -cw my_file.coffee');
coffeeProcess.stdout.on('data', function(data) {
console.log(data);
});
OR pipe the child process's stdout to the main stdout.
coffeeProcess.stdout.pipe(process.stdout);
OR inherit stdio using spawn
spawn('coffee -cw my_file.coffee', { stdio: 'inherit' });
There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn and the { stdio: 'inherit' } option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone.
Simply do this:
var spawn = require('child_process').spawn;
spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });
Credit to #MorganTouvereyQuilling for pointing this out in this comment.
Inspired by Nathanael Smith's answer and Eric Freese's comment, it could be as simple as:
var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee').stdout.pipe(process.stdout);
I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log() is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout or stderr with process.stdout.write() instead of console.log(), then you'll get the console output from the spawned process 'as is'.
I saw that solution here:
Node.js: printing to console without a trailing newline?
Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).
I have found it helpful to add a custom exec script to my utilities that do this.
utilities.js
const { exec } = require('child_process')
module.exports.exec = (command) => {
const process = exec(command)
process.stdout.on('data', (data) => {
console.log('stdout: ' + data.toString())
})
process.stderr.on('data', (data) => {
console.log('stderr: ' + data.toString())
})
process.on('exit', (code) => {
console.log('child process exited with code ' + code.toString())
})
}
app.js
const { exec } = require('./utilities.js')
exec('coffee -cw my_file.coffee')
After reviewing all the other answers, I ended up with this:
function oldSchoolMakeBuild(cb) {
var makeProcess = exec('make -C ./oldSchoolMakeBuild',
function (error, stdout, stderr) {
stderr && console.error(stderr);
cb(error);
});
makeProcess.stdout.on('data', function(data) {
process.stdout.write('oldSchoolMakeBuild: '+ data);
});
}
Sometimes data will be multiple lines, so the oldSchoolMakeBuild header will appear once for multiple lines. But this didn't bother me enough to change it.
child_process.spawn returns an object with stdout and stderr streams.
You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.
so you can solve your problem using child_process.spawn as used below.
var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('code ' + code.toString());
});
Here is an async helper function written in typescript that seems to do the trick for me. I guess this will not work for long-lived processes but still might be handy for someone?
import * as child_process from "child_process";
private async spawn(command: string, args: string[]): Promise<{code: number | null, result: string}> {
return new Promise((resolve, reject) => {
const spawn = child_process.spawn(command, args)
let result: string
spawn.stdout.on('data', (data: any) => {
if (result) {
reject(Error('Helper function does not work for long lived proccess'))
}
result = data.toString()
})
spawn.stderr.on('data', (error: any) => {
reject(Error(error.toString()))
})
spawn.on('exit', code => {
resolve({code, result})
})
})
}

Resources