How can I modify 'index.js' on '.nuxt' in order to execute cpp program which gets connected to nodejs server? - node.js

I'm a newbie to nodejs and currently working to run a certain cpp program running on a nodejs server with a click on a button.
After googling for a while, I've found that I can use something called 'Child process' to execute cpp program from a server side. And I've tried to include the following code in 'index.js' in '.nuxt' folder.
const { exec, spawn } = require("child_process");
exec('"C:\\Projects\\Monitoring_and_Diagnosis\\socketgraph\\build\\" spectrum_sim_cu', (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
const child = spawn("./spectrum_sim_cu"); //where a is the exe file generated on compiling the code.
child.stdin.write("-10 10 (5/260) 70.03 0");
child.stdin.end();
child.stdout.on("data", (data) => {
console.log(`child stdout:\n${data}`);
});
});
I thought 'index.js' would be the right place to insert the above code since my cpp program needs to run and connect with the server as the nodejs server starts up. However, the whole '.nuxt' folder seems to be refreshed when I type 'npm run dev' to run the server.
Is it the right place or approach to run the cpp program on nodejs server.
Can anyone help me out please?
Thanks in advance.

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

Detach a child process from Casperjs

I'm trying to develop an test script with casperjs that, in case of failure of a single test, sends an email to the developer.
The mailing script is made with nodejs using nodemailer.
If the function that starts the mailer is somewhere in the casperjs script it works perfectly, the problem comes when the test fails: it seems that casperjs exists without leaving the time to the child process to complete.
The only way I found to make it work is to add a --auto-exit=no and to explicitly exit when I receive the mailer response. But I'd like to avoid passing the param outside the script.
Is there a way to:
set inside the script the auto-exit option?
OR to detach the child process so that it doesn't die when the parent exits?
Listener:
casper.test.on("fail", function(failure){
casper.capture(image_dir+'/ERROR.png');
tools.sendMail(
tools.config.recipients,
'Errore '+tools.config.website,
'Il Test sul controllo login è fallito. In allegato screenshot del problema.',
'Il Test sul controllo login è fallito. In allegato screenshot del problema.',
'screenshots/login'+'/ERROR.png'
);
});
Function
var sendMail = function($to,$subject,$text,$html,$attachments) {
var childProcess;
try {
childProcess = require("child_process");
} catch (e) {
casper.echo("error"+e);
}
if (childProcess) {
childProcess.execFile("/usr/bin/nodejs", ["common/mailer.js", $to, $subject, $text, $html , $attachments], null, function(err, stdout, stderr) {
casper.echo("----------------------execFileSTDOUT:"+ JSON.stringify(stdout));
casper.echo("----------------------execFileSTDERR:"+ JSON.stringify(stderr));
casper.exit(1);
});
casper.echo("Done");
} else {
casper.echo("Unable to require child process");
}
};
I've also tried to use "nohup /usr/bin/nodejs" but with no luck.
Thanks

Using grunt to run a node server and do cleanup after

So basically this is what I want to do. Have a grunt script that compiles my coffee files to JS. Then run the node server and then, either after the server closes or while it's still running, delete the JS files that were the result of the compilation and only keep the .coffee ones.
I'm having a couple of issues getting it to work. Most importantly, the way I'm currently doing it is this:
grunt.loadNpmTasks("grunt-contrib-coffee");
grunt.registerTask("node", "Starting node server", function () {
var done = this.async();
console.log("test");
var sp = grunt.util.spawn({
cmd: "node",
args: ["index"]
}, function (err, res, code) {
console.log(err, res, code);
done();
});
});
grunt.registerTask("default", ["coffee", "node"]);
The problem here is that the node serer isn't run in the same process as grunt. This matters because I can't just CTRL-C once to terminate JUST the node server.
Ideally, I'd like to have it run in the same process and have the grunt script pause while it's waiting for me to CTRL-C the server. Then, after it's finished, I want grunt to remove the said files.
How can I achieve this?
Edit: Note that the snippet doesn't have the actual removal implemented since I can't get this to work.
If you keep the variable sp in a more global scope, you can define a task node:kill that simply checks whether sp === null (or similar), and if not, does sp.kill(). Then you can simply run the node:kill task after your testing task. You could additionally invoke a separate task that just deletes the generated JS files.
For something similar I used grunt-shell-spawn in conjunction with a shutdown listener.
In your grunt initConfig:
shell: {
runSuperCoolJavaServer:{
command:'java -jar mysupercoolserver.jar',
options: {
async:true //spawn it instead!
}
}
},
Then outside of initConfig, you can set up a listener for when the user ctrl+c's out of your grunt task:
grunt.registerTask("superCoolServerShutdownListener",function(step){
var name = this.name;
if (step === 'exit') process.exit();
else {
process.on("SIGINT",function(){
grunt.log.writeln("").writeln("Shutting down super cool server...");
grunt.task.run(["shell:runSuperCoolJavaServer:kill"]); //the key!
grunt.task.current.async()();
});
}
});
Finally, register the tasks
grunt.registerTask('serverWithKill', [
'runSuperCoolJavaServer',
'superCoolServerShutdownListener']
);

Redirecting output to a log file using node.js

I have a child process that I am using as follows in node.js. Instead of redirecting the output to the console I would like to put the output in a log file located somewhere on the machine this is running on (and should work for both windows and mac).
The code below is what I am using and I would like to output the files into a log file. What changes needed to do that here? Thanks!
My Code:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
Here's an example of logging to file using streams.
var logStream = fs.createWriteStream('./logFile.log', {flags: 'a'});
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.pipe(logStream);
ls.stderr.pipe(logStream);
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
There are two ways you can achieve this, one is using
let logConsoleStream = fs.createWriteStream('./logConsoleFile.log', {flags: 'a'});
let logErrorStream = fs.createWriteStream('./logErrorFile.log', {flags: 'a'});
and redirect all logs or errors using this
ls.stdout.pipe(logConsoleStream ); // redirect stdout/logs only
ls.stderr.pipe(logErrorStream ); // redirect error logs only
by separating log files you will have separate files for Error logs and console logs
this is exactly same as generalhenry shared above
And Second Way for Achieving this with the help of Command Line
when you execute node app from the command line
node app/src/index.js
you can specify here where you want to redirect logs and Errors from this application
there are three stream redirection commands using the command line
`>` It will redirect your only stdout or logs to the specified path
`2>` It will redirect your errors logs to the specified path
`2>&1 ` It will redirect all your stdout and stderr to a single file
example: how you will use these commands
node app/src/index.js > ./logsOnly.txt
node app/src/index.js 2> ./ErrorsOnly.txt
node app/src/index.js 2>&1 ./consoleLogsAndErrors.txt
I hope someone coming later finds this helpful
if there is I done wrong way please do let me know it will help me and others
Thanks
If you run your JS script with forever then you have the option to define a log file as parameter which will handle all your console.log messages. Not to mention the benefit of keeping your nodejs app live permanently.
Alternatively try this:
sudo forever start myapp.js 2>&1 /home/someuser/myapp/myapp.log
use forever with below options
forever start -o out.log -e err.log server.js
The best answer was in the comments and is mentioned in a previous question here: stackoverflow.com/questions/2496710/nodejs-write-to-file
It is as follows:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});

NodeJS not spawning child process except in tests

I have the following NodeJS code:
var spawn = require('child_process').spawn;
var Unzipper = {
unzip: function(src, dest, callback) {
var self = this;
if (!fs.existsSync(dest)) {
fs.mkdir(dest);
}
var unzip = spawn('unzip', [ src, '-d', dest ]);
unzip.stdout.on('data', function (data) {
self.stdout(data);
});
unzip.stderr.on('data', function (data) {
self.stderr(data);
callback({message: "There was an error executing an unzip process"});
});
unzip.on('close', function() {
callback();
});
}
};
I have a NodeUnit test that executes successfully. Using phpStorm to debug the test the var unzip is assigned correctly
However if I run the same code as part of a web service, the spawn call doesn't return properly and the server crashes on trying to attach an on handler to the nonexistent stdout property of the unzip var.
I've tried running the program outside of phpStorm, however it crashes on the command line as well for the same reason. I'm suspecting it's a permissions issue that the tests don't have to deal with. A web server spawning processes could cause chaos in a production environment, therefore some extra permissions might be needed, but I haven't been able to find (or I've missed) documentation to support my hypothesis.
I'm running v0.10.3 on OSX Snow Leopard (via MacPorts).
Why can't I spawn the child process correctly?
UPDATES
For #jonathan-wiepert
I'm using Prototypical inheritance so when I create an "instance" of Unzipper I set stdout and stderr ie:
var unzipper = Unzipper.spawn({
stdout: function(data) { util.puts(data); },
stderr: function(data) { util.puts(data); }
});
This is similar to the concept of "constructor injection". As for your other points, thanks for the tips.
The error I'm getting is:
project/src/Unzipper.js:15
unzip.stdout.on('data', function (data) {
^
TypeError: Cannot call method 'on' of undefined
As per my debugging screenshots, the object that is returned from the spawn call is different under different circumstances. My test passes (it checks that a ZIP can be unzipped correctly) so the problem occurs when running this code as a web service.
The problem was that the spawn method created on the Object prototype (see this article on Protypical inheritance) was causing the child_process.spawn function to be replaced, so the wrong function was being called.
I saved child_process.spawn into a property on the Unzipper "class" before it gets clobbered and use that property instead.

Resources