run a windows batch file from node.js - node.js

am trying to run a test.bat file inside node.js
here is the code
var exec = require('child_process').execFile;
case '/start':
req.on('data', function (chunk) {});
req.on('end', function () {
console.log("INSIDE--------------------------------:");
exec('./uli.bat', function (err, data) {
console.log(err);
console.log(data);
res.end(data);
});
});
break;
while running this node.js file am getting
INSIDE--------------------------------:
{ [Error: Command failed: '.' is not recognized as an internal or ext
nd,
operable program or batch file.
] killed: false, code: 1, signal: null }

I have found the solution for it.. and its works fine for me. This opens up a new command window and runs my main node JS in child process. You need not give full path of cmd.exe.
I was making that mistake.
var spawn = require('child_process').spawn,
ls = spawn('cmd.exe', ['/c', 'my.bat']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});

The easiest way I know for execute that is following code :
require('child_process').exec("path/to/your/file.bat", function (err, stdout, stderr) {
if (err) {
// Ooops.
// console.log(stderr);
return console.log(err);
}
// Done.
console.log(stdout);
});
You could replace "path/to/your/file.bat" by __dirname + "/file.bat" if your file is in the directory of your current script for example.

In Windows, I don't prefer spawn as it creates a new cmd.exe and we have to pass the .bat or .cmd file as an argument. exec is a better option. Example below:
Please note that in Windows you need to pass the path with double backslashes. E.g. C:\\path\\batfilename.bat
const { exec } = require('child_process');
exec("path", (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});

An easier way I know for executing that is the following code :
function Process() {
const process = require('child_process');
var ls = process.spawn('script.bat');
ls.stdout.on('data', function (data) {
console.log(data);
});
ls.stderr.on('data', function (data) {
console.log(data);
});
ls.on('close', function (code) {
if (code == 0)
console.log('Stop');
else
console.log('Start');
});
};
Process();

Related

how to execute an exe file inside node.js application

var exec = require('child process').execFile;
exec('C:\something.exe', function (err, data) {
console.log(err)
console.log(data.toString());
});
You can accomplish this by using the exec function from the built-in child_process module as shown in the NodeJS documentation.
const { exec } = require('child_process');
exec('start program.exe', (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});

child_process.spawn doesn't emit any events

I'm trying to run ripgrep from my Node app and am seeing a strange behavior with child_process.spawn: none of the events fire and the app never finishes (is stuck somewhere inside the spawn call):
import { spawn } from 'child_process';
async function run() {
await spawnWrapper('rg', ['-F', '"demo"'], { cwd: __dirname });
}
export function spawnWrapper(command, args, options) {
return new Promise((resolve, reject) => {
let stdout = '';
let stderr = '';
const child = spawn(command, args, options);
console.log('spawn wrapper');
child.on('close', (code, signal) => {
console.log('close');
resolve({ code, signal, stdout, stderr });
});
child.on('error', (error) => {
console.log('error');
(error as any).stderr = stderr;
reject(error);
});
child.on('exit', (code, signal) => {
console.log('exit');
resolve({ code, signal, stdout, stderr });
});
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (data) => {
console.log('stdout data');
stdout += data;
});
child.stderr.on('data', (data) => {
console.log('stderr data');
stderr += data;
});
});
}
I only get "spawn wrapper" in the console, no other events. I've never seen this behavior with other binaries, maybe it's something with ripgrep but still, shouldn't I be getting at least some hints by Node? Any suggestions on how to debug this?
It was caused by ripgrep waiting for input which was not obvious to me (on command line, it just executes straight away). Details here: https://github.com/BurntSushi/ripgrep/issues/410

How to execute exe of different machine from my machine in node.js

We are building an application in node js with electron. There is another software which is installed in all other machines.Now in my node js application i want to launch those software on there respective machines.Is it Possible?
You could do this via commands and a child process via spawn.
See â–¶NodeJs API Docs
On Windows
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}`);
});
Linux
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
Below code worked as charm for me.
var cmd = require('node-cmd');
cmd.get('WMIC /node:"ABC-XXXXXXX" process call create "C:\\Setup\\app7.exe"',function(err, data, stderr){
console.log('err:', err)
console.log('stderr:', stderr)
})
Remote machine name : ABC-XXXXXXX
Path of exe on remote machine: C:\Setup\app7.exe

nodejs child process executing multiple times

I'm using node child process to execute a python process get a url is reached. The thing is i'm getting the process running multiple times even though the url is being reached just one time.
Here is the code:
server.get('/', function(req, res, next) {
console.log('spawning process');
var child = exec('python reporter.py', function(error, stdout, stderr) {
if (error || stderr) return console.log(error, stderr);
var data = JSON.parse(stdout);
console.log('Process ready');
});
});
It's possible that whatever you're using to send the GET response, is retrying that request when it's not getting a response. So put in a response:
e.g.
server.get('/', function(req, res, next) {
console.log('spawning process');
var child = exec('python reporter.py', function(error, stdout, stderr) {
if (error || stderr) return console.log(error, stderr);
var data = JSON.parse(stdout);
console.log('Process ready');
res.status(200).send()
});
});
For anyone who is facing the same issue in the latest version of node:
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
as per nodejs.org
// Capture your data in "data" and try putting your response in the "close".
Close gets executed when all the data processing is completed.

Execute parse develop command on nodejs

I'm using Parse as backend but their log system is hard to read. So I tried to execute the command "parse develop " inside a nodejs script to make what they log more readable but I can't make it work.
// var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
var child = exec('parse', ['develop', 'MyApp']);
child.stdout.on('data', function (data) {
console.log('This is never called');
});
child.stderr.on('data', function (data) {
console.log('This works');
});
Is there anything I am missing?
Thanks in advance.
You should use spawn instance of exec
var spawn = require('child_process').spawn,
parse = spawn('parse-develop',['MyApp']);
parse.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
parse.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
parse.on('close', function (code) {
console.log('child process exited with code ' + code);
});

Resources