How can I execute node file from nw application - node.js

I have created a nw.js desktop application. My requirement is to read data from HID devices. So am using node-hid module. I have written code specific to read and parsing data in usbreader.js file.
In my main.html file am trying to execute node command like below:
exec = require('child_process').exec;
exec('node usbreader.js', function(error, stdout, stderr) {
if (error !== null) {
console.log(stderr);
}
else{
console.log(stdout);
}
});
But am getting error saying:
'node' is not recognized as an internal or external command, operable
program or batch file.
Please help me how can I execute this node js file from nw application

If your usbreader is compatible with your nwjs node version, then you can use it in next way:
usbreader = require('usbreader');
If you want to run it in separate process in node, then you need to install node for your OS. And code is next;
exec = require('child_process').exec;
var usbreaderProc = exec('node usbreader.js', { cwd: '/path/to/usbreader/dir' } function(error, stdout, stderr) {
if (error !== null) {
console.log(stderr);
}
else{
console.log(stdout);
}
});

Related

Unable to trigger NodeJS based BATCH/Exe file using jenkins

Im trying to execute the my batch/exe file through NodeJS script by using the:
var child_process = require('child_process');
i.e.
child_process.execFile For exe
child_process.exec For Batch file
When I'm trying to execute my scripts by using followings TWO method:
Triggering via CMD it will be get executed successfully.
Triggering via Jenkins it will NOT get executed.
In both cases directory is same.
I have been using the followings function for this purpose:
exports.exec_exe_file = exec_exe_file = function(exe)
//child_process.execFile(exe, function(error, stderr, stdout) {
child_process.exec(exe, function(error, stderr, stdout) { if (error) {
console.error('stderr', stderr); throw error; } //console.log('stdout',
stdout); });
}
Called as:
var autoit = __dirname + "\\autoit\\start_AutoitExe.bat";
//var autoit = __dirname + '\\autoit\\Script.exe';
exec_exe_file(autoit);

Having trouble running child process command

I am trying to execute a nodejs file called create-MySwitch.js through a child process in my main.js file.
this is the code for main.js
const exec = require('child_process').exec;
var cmdStr = 'node /home/pi/Desktop/lan-device/create-MySwitch.js';
exec(cmdStr,
{argv: {
port:8080,
uuid:'MyThing'
}},
(error, stdout, stderr)=>{
if (error) {
console.error('exec error: ${error}');
console.log(error);
return;
}
console.log('stdout: ${stdout}');
console.log('stderr: ${stderr}');
});
This is how I am attempting to access the arguments in the create-MySwitch.js file
var port_value = process.argv.port;
var uuid_value = process.argv.uuid;
The output is
stdout: ${stdout}
stderr: ${stderr}
when I run the command
node main.js
I do not think it's working because the output from executing the create-MySwitch.js file should be 'ready', but clearly is not being printed in the stdout variable from the child process.
Essentially, what I am trying to do is run the command 'node createMySwitch.js ', but instead of just typing this in to the command prompt I want to run that command using a child process.
I am doing all of this using the raspbian operating system.

Changing command prompt directory from Node.js script

I'm trying to change the directory of terminal using with Node.js program but not able to achieve it. Script is run as node app.js dir_name so first I'm creating the directory and then trying to change into that directory using cd command. Directory is created but the directory for terminal is not changed.
#!/usr/bin/env node
var platform = process.platform;
var figlet = require('figlet');
var chalk = require('chalk');
if(process.argv.length < 3){
console.log(
chalk.green(
figlet.textSync('mdcd', { horizontalLayout: 'full' })
)
);
console.log(chalk.red("Please provide a directory name"));
}else{
if(platform.includes("win")){
//console.log("Its Windows");
}else {
var exec = require('child_process').exec;
var command_1 = "mkdir "+process.argv[2];
var command_2 = "cd "+process.cwd()+"/"+process.argv[2];
exec(command_1, function (error, stdout, stderr) {
if(error){
console.log("Something bad happened"+error);
}else {
exec(command_2, function (error, stdout, stderr) {
if(error){
console.log("Something bad happened"+error);
}
});
}
});
}
}
command prompt directory from Node.js script
You cannot change the command prompt directory. Basically you have the process tree:
cmd / term
| -> NodeJs
You shouldn't change the working dir for cmd. However there are command you can execute to change the working dir of any process e.g. https://unix.stackexchange.com/a/282009
More
You can however change the the working dir for the nodejs process (which is what I suspect you want to do) using process.chdir https://nodejs.org/api/process.html#process_process_chdir_directory

How to run shell script file using nodejs?

I need to run a shell script file using nodeJS that executes a set of Cassandra DB commands. Can anybody please help me on this.
inside db.sh file:
create keyspace dummy with replication = {'class':'SimpleStrategy','replication_factor':3}
create table dummy (userhandle text, email text primary key , name text,profilepic)
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec callback.
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
EDIT
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
Also, you can use shelljs plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix
shell commands on top of the Node.js API. You can use it to eliminate
your shell script's dependency on Unix while still keeping its
familiar and powerful commands. You can also install it globally so
you can run it from outside Node projects - say goodbye to those
gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

nodejs command line module not giving stdout

I have set up a command line node module and when I run it one of the tasks is to start up the server and log to the console. However I find that although it starts up my server fine, it does not send the output to the console.
#! /usr/bin/env node
var userArgs = process.argv.slice(2);
var searchPattern = userArgs[0];
if(userArgs[0] === "start"){
var exec = require('child_process').exec;
exec('node ./server.js',
function(err, stdout, stderr) {
console.log('stdout: ', stdout);
console.log('stderr: ', stderr);
if (error !== null) {
console.log('exec error: ', error);
}
}
);
}
So if I npm link my module then run mymodule start it starts the server fine but as I mentioned no output to the console.
Whereas if I run simply node server.js I get the output which is server listening on http://localhost:5000.
From the documentation, regarding the callback you are passing to 'exec'
'callback' - Function called with the output when process terminates
From what I understand, the process has to be terminated before you see 'stdout:' and 'stderr:' (you would have to stop the node process).

Resources