How do invoke script with another node script? - node.js

I have an node app that runs as a cron job every few seconds:
var CronJob = require('cron').CronJob;
new CronJob('*/5 * * * * *', function(){
console.log('Here invoke a script called requestdata');
}, null, true, "America/Los_Angeles");
and I just want to call a script without invoking functions on it. So its not
requestdata.foo();
but just call requestdata in same directory. how is this done? If it was on command line I would just do:
node requestdata
but how do I do this inside another script?

Use child_process, like so
var cp = require('child_process');
cp.fork(__dirname + '/request data.js');
See http://nodejs.org/api/child_process.html

This solution also shows how to pass parameters to the "request data.js" script
var cp = require('child_process');
cp.fork(__dirname + '/request data.js',[array,of,string,prams]);

Related

child_process.execSync(start "" "example.exe") freezing/locking console with executables have params option

When I try to execute an executable that have an option to have parameters. It will freeze the nodejs output and input until the executable is closed. Executables that do not need params will just run, and the nodejs console will not freeze/lock input nor output.
Example with param: test.exe -thisisaparam. Example without Params: test.exe.
Here is my code below. (Its a cli)
const cp = require('child_process');
let start = async function (start) {
let command = `start "" ${start}`;
cp.execSync(command);
console.log("Returning to menu in 10 seconds...")
setTimeout(() => {
run()
}, 10000);
};
Here is how I call the function.
async function startTest() {
await start("C:\users\user\downloads\test_param.exe")
}
Thanks, Kiefer.
Any command you run using execSync will be synchronous meaning it will wait for the command to exit and then returns the output.
If you don't need the output of the command and want to just start and detach you should use spawn with unref().
example:
const scriptPath = "C:\users\user\downloads\test_param.exe"
cp.spawn('start', [scriptPath], {detached: true, stdio: 'ignore'}).unref()

How can I replace node-cron with a command line script in a node.js application

I would like to change the implementation shown below to using a command line script in a node.js application. How do I do it?
var cron = require('node-cron');
cron.schedule('* * * * *', () => {
getBananas();
});

Trouble writing a file with CronJob in Heroku using writeFileSync()

I am trying to repeatedly update a file using a cronjob. Eventually, this is going to be more complicated but for now I'm trying to figure out my current problem. I know the code below is somewhat over-complicated because I preserved the basic structure while trying to problem solve. Here is the server file:
// server.js
var express = require('express');
var port = process.env.PORT || 8080;
var http = require('http');
var fs = require("fs");
var curtainup = require('./diagnoseleak.js');
var url = require("url" );
var app = express();
// launch ======================================================================
app.listen(port);
//run the CronJob
var CronJob = require('cron').CronJob;
new CronJob('0 * * * * *', function() {
console.log("running");
var date = new Date();
console.log("Ran at: "+date.getHours()+":"+date.getMinutes());
curtainup.doitnow();
} , null, true, 'America/New_York');
And here is the file referenced called diagnoseleak.js:
var fs = require("fs");
var mostRecentLocation = "./config/pullfiles/mostRecent55.txt";
module.exports = {
doitnow: function(){
var writethefile = function(){
fs.writeFileSync(mostRecentLocation, "A file called mostRecent55 should be create with this text", { flag: 'w' });
console.log("This should write to the console");
}
writethefile();
}
}
From the directory that houses the server file, I type the following into cmd:
git add .
git commit -m "adding files"
git push heroku master
heroku run bash
Then into the bash window I type:
cd config/pullfiles
ls -l
AND...no file called mostRecent55.txt appears. Am I looking in the wrong place? Eventually I want to be able to update a file, but I have a feeling I'm either looking in the wrong place for this mostRecet55.txt file or going about the process of writing it incorrectly.
heroku doesn't let you write files onto the filesystem where your app is stored. You would need to use an add-on, database or external service of some kind. The only exception seems to be /tmp which is only temporary storage

How to create application level variable in node.js

In my project I have running more than 100 cron jon using npm cron. My problem is I need to stop any cron job at run time.
my code is
in app.js file
var cronJobRunner =require('cronJobHandle.js');
global.jobManager = {};
cronJobRunner.startServiceFromCronJobManager("service 1")
in cronJobHandle.js
var CronJob = require('cron').CronJob;
module.exports = {
startServiceFromCronJobManager: function (scheduleServiceName) {
var serviceList =['service1','service2','service3','service4']
serviceList.forEach(function(service){
var job = new CronJob('* * * * * *', function(){
console.log("Service running");
}, function () {
// This function is executed when the job stops
},
true /* Start the job right now */,
timeZone /* Time zone of this job. */
);
global.jobManager.service = job;
});
},
stopServiceFromCronJobManager: function (scheduleServiceName) {
console.log(global.jobManager);
global.jobManager[scheduleServiceName].stop();
}
};
router.js
var cronJobRunner =require('cronJobHandle.js');
app.route('/stopservice',function(req,res){
cronJobRunner.stopServiceFromCronJobManager("service1");
}
When I call http://localhost:9999/stopservice
I am getting undefine in console.log(global.jobManager);
Please help me how to maintain cron jobManager variable comman for all server side js files
It is global but there's two bugs in your code.
1) you're calling the property called "service" instead of the one whose name is in service.
Change
global.jobManager.service = job;
to
global.jobManager[service] = job;
2) you're pottentially using global.jobManager in cronJobHandle.js before to declare it in app.js
There's a better solution. you don't need and should use global. Just declare a standard variable in cronJobHandle.js instead (so that it isn't accessed by other modules):
var jobManager = {};
...
jobManager[service] = job;
...
jobManager[scheduleServiceName].stop();

how do I make node child_process exec continuously

How to exec continuously? e.g. ls after cd?
I tried
exec = require('child_process').exec;
exec('cd ~/',
function(){
exec('ls'),
function(err, stdout, stderr){
console.log(stdout); // this logs current dir but not ~/'s
}
}
)
exec('cd ~/').exec('ls', function(err, stdout, stderr){
console.log(stdout);
})//this also fails because first exec returns a ChildProcess Object but not itself.
It is not possible to do this because exec and spawn creates a new process. But there is a way to simulate this. You can start a process with exec and execute multiple commands in the same time:
In the command line if you want to execute 3 commands on the same line you would write:
cmd1 & cmd2 & cmd3
So, all 3 commands run in the same process and have access to the context modified by the previous executed commands.
Let's take your example, you want to execute cd ../ and after that to execute dir and to view the previous directory list.
In cmd you shoud write:
cd../ & dir
From node js you can start a process with exec and to tell it to start another node instance that will evaluate an inline script:
var exec = require('child_process').exec;
var script = "var exec = require('child_process').exec;exec('dir',function(e,d,er){console.log(d);});";
script = '"'+script+'"';//enclose the inline script with "" because it contains spaces
var cmd2 = 'node -e '+script;
var cd = exec('cd ../ &'+cmd2,function(err,stdout,strerr)
{
console.log(stdout);//this would work
})
If you just want to change the current directory you should check the documentation about it http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
You can use nodejs promisify and async/await:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
export default async function () {
const cpu = await exec('top -bn1');
const disk = await exec('df -h');
const memory = await exec('free -m');
const payload = {
cpu,
disk,
memory,
};
return payload
}
If you want to use cd first, better use process.chdir('~/'). Then single exec() will do the job.
You can call exec with cwd param like so:
exec('ls -a', {
cwd: '/Users/user'
}, (err, stdout) => {
if (err) {
console.log(err);
} else {
console.log(stdout);
}
})
But beware, cwd doesn't understand '~'. You can use process.env.HOME instead.

Resources