NodeJS passing command line arguments to forever - node.js

Im trying to pass command line arguments to forever, that I want to parse in my app.
Currently I'm starting my app like this:
forever start -c "node --max-old-space-size=8192 --nouse-idle-notification" /home/ubuntu/node/server.js
I want to be able to read some arguments in my server.js.
My code for reading:
var arguments = process.argv.slice(2);
console.log(arguments[0]);
if(!arguments[0]) {
console.log("Error: Missing port.");
process.exit(1);
}
But how to I tell forever to pass arguments that can be read inside server.js?

According to the forever docs, you should use this format where you append your script arguments to the very end:
forever [action] [options] SCRIPT [script-options]
So for your example, you should be able to do this (omitting the -c options to make this a little more readable):
forever start server.js 9000 anotherarg evenanother
You can add the -c and the full path to server.js back into your real call, based upon your situation.

Related

how to pass shell script variable to node app.js?

I have prepared the shell script to launch the node application (written using express framework). Shell script looks like below-
#!/bin/bash
cd <NODE.JS Project directory>
npm install --save
var1="connect_point1";
var2="connect_point2";
node app.js var1 var2
in app.js have included below lines-
//print process.argv
process.argv.for Each((val, index) => {console.log('${index}: ${val}');});
var cp1=var1;
var cp2=var2;
I am unable to get var1,var2 values which is passed from shell script to use it in node app.js script. Please suggest me correct way to achieve this.
In the log can see the variable var1 and var2 not defined. so issue is when i am trying to pass the shell script variable to node app.js script..pls suggest me how to pass those parameter correctly, so it can be used in ap.js and other subsequent node scripts.
Add a $ sign to your arguments inside bash script to indicate variables.
#!/bin/bash
var1="connect_point1"
var2="connect_point2"
node app.js $var1 $var2
app.js
process.argv.forEach((index, value) => console.log(index, value));
This is the output i see when running the above bash script:
./bash_script.sh
/usr/local/Cellar/node/12.4.0/bin/node 0
/Users/Username/Temp/app.js 1
connect_point1 2
connect_point2 3
here you can see that the argument values you need are located on index 2 and 3:
var cp1 = process.argv[2];
var cp2 = process.argv[3];

Node.JS reading data from console command

I remember using something before in node.js that would allow me to run a command like
node appname.js text goes here
and then read the "text goes here" part with something like
console.log(console.text)
I can't remember what it is, and can't find it in any searches. Was this a real thing, or just me dreaming?
You can use process.argv to console the input from command line.
If you run below command in terminal/command line:
node appname.js text goes here.
You can print the command line arguments by:
console.log(process.argv)
Output of above console will be:
['node',
'/home/user/path/to/appname.js',
'text',
'goes',
'here' ]
If you dont want first two text, you can use:
console.log(process.argv.slice(2))
Output of above console will be:
['text',
'goes',
'here' ]
Read this link for more info.
Hope this helps you out!!!
Well there is lot's ways/packages around for reading from arguments.
the nodejs process is the base of it so check here
And also as i said lot's of packages there for parsing arguments.
yargs is one of them, minimist is also a populer one as far as i know.
If you don't want t use a package basicly it starts like this:
// inside node file
const args = process.argv.splice(2);
console.log(args);
// we are splice'ing from 2 cause
// process.argv[0] is your node-path
// process.argv[1] is your js file's full path
// Most of the time we are not using those so :)
So hope these would work for you ☺

How to get mongo shell output(three dot) for unterminated command

When type a unterminated command in a mongo shell, it will return three dots indicating need more input to complete this command like below:
> db.test.find(
... {
...
I am using nodejs child_process.spawn to create a mongo shell process and listen on its output. I can get the standard and error output from the mongo shell but I can't get the ... output. Below is my nodejs code:
const shell = spawn('mongo', params);
shell
.stdout
.on('data', (data) => {
winston.debug('get output ' + data);
});
shell
.stderr
.on('data', (data) => {
const output = data + '';
winston.error('get error output ', data);
});
I run below code to send command on the shell:
shell.stdin.write('db.test.find(');
I wander why I can't get the ... output on above method. Is it a special output?
EDIT1
I tried to use node-pty and pty.js. They can get the ... output but they mix the input and output data together. It is not possible to separate them.
I also tried to use stdbuf and unbuffer to disable buffer but it still doesn't work.
It seems that nodejs child_process doesn't work well with interactive command.
Your code doesn't include anything that writes to the stdin of your child process so I would be surprised if you got the ellipsis that indicates incomplete command when in fact you don't send any command at all - incomplete or otherwise.
That having been said, many command line utilities behave differently when they discover a real terminal connected to their stdin/stdout. E.g. git log will page the results when you run it directly but not when you pipe the results to some other command like git log | cat so this may also be the case here.
This can also have to do with the buffering - if your stream is line-buffered then you won't see any line that is not ended with a newline right away.
The real question is: do you see the > prompt? Do you send any command to the mongo shell?
Scritping interactive CLI tools can be tricky. E.g. see what I had to do to test a very simple interactive program here:
https://github.com/rsp/rsp-pjc-c01/blob/master/test-z05.sh#L8-L16
I had to create two named pipes, make sure that stdin, stderr and stdout are not buffered, and then use some other tricks to make it work. It is a shell script but it's just to show you an example.

Prereload script into node interactive mode

Is it possibille to run node.exe, pipe a text into it, and continue the interactive session?
I want to create a shortcut bat (or bash) file for editing my database.
Usually this is what I'm doing:
$ node
>var db=require('mydb')
>db.open('myserver')
>//Now I can start access the db
>db.query...
I want to do something like that:
$ node -i perDefinedDb.js
>db.query(.... //I don't want to define the DB each time I run the node.exe
I tried some like that:
echo console.log(a) | node.exe
This is the result:
3
And the program is Finish. I want to continue the node REPL after piping something into.
In Other Words:
I want to be able to use my DB from node REPL, without defining it each time.
Launch the REPL from your js file and you can give the context you want:
const repl = require('repl');
var db = require('mydb');
db.open('myserver');
repl.start('> ').context.db = db;
Now you just have to run this file (node myREPL.js) and you can REPL as usual.

NodeJS and Forever (monitoring and restarting app)

I'm trying to setup forever and NodeJS to monitor&restart my app and also keep it running when exits. Currently I have this:
var forever = require("forever-monitor");
var child = new(forever.Monitor)('main.js', {
'silent': false,
'pidFile': '../pids/app.pid',
'sourceDir': '.',
'watch': true,
'watchDirectory': '.',
'watchIgnoreDotFiles': null,
'watchIgnorePatterns': null,
'logFile': '../logs/forever.log',
'outFile': '../logs/forever.out',
'errFile': '../logs/forever.err'
});
child.start();
Which starts my app just fine but it doesn't restart it when I make changes in the file. Is there some option that I'm missing?
EDIT:
After digging into the problem I found that the file change is detected actually, it's just that the process isn't restarted.
I'm looking at line ~317 - Monitor.prototype.kill (in monitor.js) but everything looks like it should work.
EDIT:
I managed to fix the issue. It's a bug in the library's code. Check here: https://github.com/nodejitsu/forever-monitor/issues/27
nodemon and forever are a pain to get running consistently. I would try using a shell script first. If you are on linux, just place a monitornode file in /etc/cron.d
*/1 * * * * root /var/www/nodejs/monitornode.sh
and have a script somewhere on your machine
Try this if you are getting started, create a file /var/www/nodejs/monitornode.sh and chmod +x :
#!/bin/sh
TT_NODE="node /var/www/nodejs/node.js"
# NODEJS Watcher
if [ -z `pgrep -f -x "$TT_NODE"` ]
then
echo "Starting $TT_NODE."
cmdNODE="$TT_NODE >> /var/www/logs/node.log &"
eval $cmdNODE
fi
Check out the nodemon package to do the whole "reload on file change" thing.

Resources