Node - child process spawn path - javascript

I would like to run an exe in Windows from my Node Webkit app.
I am trying the below code but it is not working.
document.getElementById('play').onclick = function()
{
var spawn = require('child_process').spawn;
var child = spawn(__dirname + '/core.exe', ['/arg1']);
var snd = new Audio("min.wav");
snd.play();
win.minimize();
child.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
child.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
child.on('close', function (code) {
console.log('child process exited with code ' + code);
var snd = new Audio("restore.wav");
snd.play();
win.restore();
});
}
Am I getting the path wrong? I need it to be current directory and run the exe with that name and the example arg.
The output SHOULD be a messagebox, but nothing loads.

Managed to figure it out, it wasn't defined because I was using it in browser context. I didn't get the nw.js SDK version for some reason, found that __DIRNAME was undefined. Came up with this solution instead.
var path = require('path');
var nwDir = path.dirname(process.execPath);
var spawn = require('child_process').spawn;
var child = spawn(nwDir + '/app/core.exe', ['/arg1']);
Now working as intended.

Related

Problem using child-process vs terminal while executing a command

I try to execute a command using a child-process and I can't execute by absolute path using nodejs, but when I use terminal, everything is fine.
Why is that?
My code is right here:
const cp = require('child_process');
const commandExecutor = 'node-install/target/node/yarn/dist/bin/yarn.exe';
const symlinkFolder = 'node-install/target/node/target/symlink';
const workingDirectories = [];
Array.from(process.argv).forEach((value, index) => {
if (index >= 2) {
workingDirectories[index - 2] = value;
}
});
workingDirectories.forEach(function(workingDirectory) {
const argumentsUnlink = 'unlink #item# --link-folder ' + symlinkFolder + ' --cwd ' + workingDirectory;
const unlinkCommand = commandExecutor + ' ' + argumentsUnlink;
const execution = cp.exec(
unlinkCommand,
function (error, stdout, stderr) {
console.log(stdout);
console.log(error);
console.log(stderr);
});
execution.on('exit', function (code) {
let message = 'Child process exited with exit code ' + code + ' on route ' + workingDirectory;
console.log(message);
});
});
An example of command is:
node-install/target/node/yarn/dist/bin/yarn.exe unlink #item# --link-folder node-install/target/node/target/symlink --cwd appointments/target/generated-sources/frontend/
But the error I've got is:
'node-install' is not recognized as an internal or external command, operable program or batch file.
While I execute command from terminal, everything is fine.
One of the possible problems - NodeJs unable to locate the file by relative path. You can use construct absolute path to fix this, few options to help if node-install is located in your project root (not ultimate list):
__dirname, which returns the directory of current module, so if
node-install/../..
index.js
then in index.js we can use
const commandExecutor = `${__dirname}/node-install/target/node/yarn/dist/bin/yarn.exe`;
process.cwd(), which returns full path of the process root, so if you start nodejs from folder having node-install, then you can refer to exe like this:
const commandExecutor = `${process.cwd()}/node-install/target/node/yarn/dist/bin/yarn.exe`;

Not able to create child Process in node.js

I am working on a log tail project using node.js but the function process.createChildProcess is not working.Is there any alternative to that?
var sys = require('sys');
var filename = "test.txt";
var process=require('process')
if (!filename)
return sys.puts("Usage: node watcher.js filename");
// Look at http://nodejs.org/api.html#_child_processes for detail.
var tail = process.createChildProcess("tail", ["-f", filename]);
sys.puts("start tailing");
tail.addListener("output", function (data) {
sys.puts(data);
});
// From nodejs.org/jsconf.pdf slide 56
var http = require("http");
http.createServer(function(req,res){
res.sendHeader(200,{"Content-Type": "text/plain"});
tail.addListener("output", function (data) {
res.sendBody(data);
});
}).listen(8000);
Here I am getting error:
var tail = process.createChildProcess("tail", ["-f", filename]);
^
TypeError: process.createChildProcess is not a function
Any help will be appreciated
Article referred: https://thoughtbot.com/blog/real-time-online-activity-monitor-example-with-node-js-and-websocket
You can use spawn for creating a child process in Node.JS.
Here's an example based on your code:
const { spawn } = require('child_process');
/* Some Code Here! */
var tail = spawn("tail", ["-f", filename]);

IPFS in Javascript 'cat' function doesn't work

I created this testcase to prove that the cat method is not working for me using the IPFS javascript library. What am I doing wrong ? My console output does not draw anything from within the 'node.files.cat' function, its as if that (err,filestream) callback is not being called at all. I I know my multihash is somewhat working because if I change it I get a fatal error. However right now it is seemingly just locking up and pausing after NODE READY.
const IPFS = require('ipfs')
const path = require('path')
const os = require('os')
const fs = require('fs')
console.log('ipfs test ')
var mhash = "Qmc5LfkMVAhvzip2u2RjRBRhgVthtSokHsz4Y5bgaBCW2R";
// Create the IPFS node instance
const node = new IPFS()
node.on('ready', () => {
// Your node is now ready to use \o/
console.log('NODE READY')
/*
THIS WORKS
var test_rstream = fs.createReadStream( path.join(__dirname, '.', '/public/sample_land_file.json') )
var wstream = fs.createWriteStream(os.tmpdir() + '/lobc_cache/'+'Qmc5LfkMVAhvzip2u2RjRBRhgVthtSokHsz4Y5bgaBCW2R');
wstream.on('finish', function() {
console.log('Written ' + wstream.bytesWritten + ' ' + wstream.path);
test_rstream.close()
});
test_rstream.pipe(wstream);
*/
node.files.cat("Qmc5LfkMVAhvzip2u2RjRBRhgVthtSokHsz4Y5bgaBCW2R", function (err, filestream) {
console.log('WHY ISNT THIS FIRING ') // i never see this logged
console.log(filestream)
console.log(os.tmpdir())
if (!fs.existsSync(os.tmpdir() + '/lobc_cache')){
fs.mkdirSync(os.tmpdir() + '/lobc_cache');
}
var wstream = fs.createWriteStream(os.tmpdir() + '/lobc_cache/'+'Qmc5LfkMVAhvzip2u2RjRBRhgVthtSokHsz4Y5bgaBCW2R');
result = '';
wstream.on('finish', function() {
console.log('Written ' + wstream.bytesWritten + ' ' + wstream.path);
filestream.close()
});
filestream.pipe(wstream);
// wstream.end();
// file will be a stream containing the data of the file requested
})
// stopping a node
node.stop(() => {
// node is now 'offline'
})
})
node.on('start', () => {
console.log('NODE START')
})
This looks like a bug. A quick way to solve it is just to put the node.files.cat inside the callback for .on('ready'). Seems that bitswap is dropping requests before the node is online.
Let me know if this works.

How to kill child_process in node.js -- req.on close

I am trying to kill the child process when "requst.on('close' " is called. But child.pid inside this callback always points to most recent request. The question is: how can I match the child.pid to the request? Thanks
var query_script = "query.py"
var express = require('express');
var app = express();
var spawn = require('child_process').spawn;
app.get('/:version/query', function(request, response) {
child = spawn('python, ['query.py', request.originalUrl])
console.log("start pid=" + child.pid + ": " + request.originalUrl)
request.on('close', function () {
console.log("1: current pid=" + child.pid)
//child.kill('SIGTERM');
})
child.stdout.pipe(response)
});
app.listen(3000);
console.log('Listening on port 3000...');
Define child within your closure by putting var in front of it.
var child = spawn('python, ['query.py', request.originalUrl])

Node.js can't get output of spawned process

This code get output of spawned process. What is wrong? node version is v0.10.22
var spawn = require('child_process').spawn;
var what = 'java';
var spawned = spawn(what, ['-version']);
console.log('starting `'+what+' -version`');
spawned.stdout.setEncoding('utf8');
spawned.stdout.on('data', function (data) {
console.log(data);
});
spawned.on('close', function (code) {
console.log('process exit code ' + code);
});
var whendone = function() {
console.log('done');
};
setTimeout(whendone,5000);
As you can see I even added some timeout to wait for a launched process to finish.
java -version writes to stderr.

Categories