Execute parse develop command on nodejs - node.js

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);
});

Related

How to send command to child process nodejs

I am making an application that handles java commands and want to send java command to my child spawn process how can i achieve this
const {
spawn
} = require('child_process');
// Start child process
var child = spawn('java', ['-server', '-Xms1G', `-Xmx${document.getElementById('ram').value}G`, `-jar`, `${jarname}`], {
cwd: `${jarfolder}`
});
child.stdout.on('data', (data) => {
$("ol").append(`<li>${data}</li><br>`);
});
child.stderr.on('data', (data) => {
$("ol").append(`<li>${data}</li><br>`);
});
child.on('error', (error) => console.log(`error: ${error.message}`));
child.on('exit', (code, signal) => {
if (code) $("ol").append(`<li>Process exit with code: ${code}</li><br>`);
if (signal) $("ol").append(`<li>Process killed with signal: ${signal}</li><br>`);
});
demo code
example i have a button that calls a function and
function test(){
var command=document.getElementsById("command").innerHTML;
// send the command to terminatal

Node error: illegal or missing argument for command line flat. switch

I am reeving error when using spawn in Node.js 4.4.4
Node error: illegal or missing argument for command line flat. switch
Here my code:
var bat = require.resolve('../src/util/bs/build.bat');
var profile = require.resolve('../profiles/profile.js');
var profileStr = '--profile' + ' ' + profile;
var ls = spawn(bat, [profileStr]);
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 .bat file run properly when called from command prompt like:
"C:\Projects\xxx\src\util\bs\build.bat --profile C:\Projects\xxx\profiles\app.profile.js"
I was able to solve this issue passing arguments to .bat using an array.
Example:
var bat = require.resolve('../src/util/bs/build.bat');
var profile = require.resolve('../profiles/profile.js');
var ls = spawn(bat, ['--profile', profile]);
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);
});

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.

How to capture response from child process in nodejs

I am trying to capture some response from my child process in master process. I can log information of child process in master process but unable to capture some return xyz response .
Here is code for master process:
var express = require('express');
var app = express();
const
fs = require('fs'),
cp = require('child_process');
app.get('/',onRequest );
function onRequest(request, response) {
var express = require('express');
var app = express();
var child= cp.spawn('node' ,['./child_process/block.js'],filestreamCallback);
child.stdout.on('data', function(data) {
console.log('stdout: ==== ' + data);
});
child.stderr.on('data', function(data) {
console.log('stdout: ' + data);
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
function filestreamCallback() {
response.writeHead(200, {'Content-Type': 'text/plain'});
baflog.info("Reading Stream completed");
response.write('Thanks for Your patience!\n');
response.end();
}
}
app.listen(5000);
console.log('Server started');
Child process : block.js
/*Keep waiting for 10 seconds*/
console.log("Waiting for child Process (block.js) to complete......");
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 10000);
ret_resp();
var response = {status:'success'};
function ret_resp(){
return response;
}
console.log("Thank You for waiting......");
Like in console i see output as :
stdout====: Waiting for child Process (block.js) to complete......
-punws-sohan
stdout: ==== Thank You for waiting......
I cannot see output for return response statement
Can anyone suggest how to capture response from child process?
First of all, the busy loop uses up unnecessary CPU time. Just use a setTimeout() instead. Example:
setTimeout(function() {
ret_resp();
// ...
}, 10000);
Secondly, you can't expect return to magically write the returned value to the parent process. Try this instead:
// parent.js
var child = cp.fork('./child_process/block.js', [], { silent: true });
child.stdout.on('data', function(data) {
console.log('stdout: ==== ' + data);
});
child.stderr.on('data', function(data) {
console.log('stdout: ' + data);
});
child.on('message', function(msg) {
console.log('message from child: ' + require('util').inspect(msg));
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
// child.js
console.log('Waiting for child Process (block.js) to complete......');
setTimeout(function() {
var response = {status:'success'};
function ret_resp() {
process.send(response);
}
ret_resp();
console.log('Thank You for waiting......');
}, 10000);

run a windows batch file from 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();

Resources