Make nodemon auto-restart a program on crash without waiting for file changes at custom error? - node.js

I'm building an E-commerce site, where there's an Authentication system.
I noticed that if the client login with a wrong user or password, the backend/server that works with nodemon will crach and hang in there crashed till i restart manually nodemon. This is example output error of the nodemon crash:
[nodemon] app crashed - waiting for file changes before starting...
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
to the client
Ofcourse, when server crashes, client can no more access or do login again till server restarts.
After some googling, i found this question and this repository that fix my problem but particulary and not as expected precisely, i dont want nodemon to restart forever on any error that occure ofcourse, but only with specifics errors that i set them -like Authentication errors as i mentionned above-.
So, my idea/question is: is there anyway to get nodemon restarts by itself in some cases of failures or errors (NOT ALL)?

Seems like you a referring to a production situation, and nodemon is a development node server, which is not intended for use in production, as the intro states:
nodemon is a tool that helps develop Node.js based applications by
automatically restarting the node application when file changes in the
directory are detected.
You should use node.js in production, instead of nodemon.
For managing your node server in production, you could use a process manager like PM2..
That said, an authentication server that crashes every time a user uses a wrong password seams very ineffective in handling a common use case. So I would advise to start with fixing the root cause, which is the buggy server, and then for recovery from incidental crashes use something like PM2.
PS:
The error you are getting looks like an express error you get when you send a response (in this case an error response) without exiting the function e.g. by using return. Because you are not returning, another res.send is called, which causes the 'ERR_HTTP_HEADERS_SENT' error. See this answer.

This is really bad since it can send your program into a loop of restarting, but if you really want it, replace app.js with your file's name and try this:
nodemon -x 'node app.js || copy /b app.js +,,'
Linux version:
nodemon -x 'node app.js || touch app.js'
Next time try a little googleing before you ask since it is most likely faster.

Related

Next.js/React application with pm2: SyntaxError: Unexpected token '<'

I'm new to next.js and react. I have created a simple application and would like to serve it using pm2 and Apache.
When I run npm run dev in the folder of the next project, the server starts and I can see my application on port 3000 of localhost.
However, when pm2 attempts to run the application (I have set it to run on server boot), I get the following error in the pm2 logs:
SyntaxError: Unexpected token '<'
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:468:14)
at async link (node:internal/modules/esm/module_job:67:21)
node --version is v16.19.0
npm --version is 8.19.3
Can someone help me to fix this issue? I don't understand why it is happening at the moment.
Without providing more information and context, it will be difficult to diagnose exactly what is going wrong. If you want good answers, you need to list out a more comprehensive list of things you've tried and information about how you are setting up nextjs with pm2.
But right now, the character is your best clue. "<" hints at the problem likely being that html markup is being loaded somewhere it shouldn't be.
I fixed it. I had neglected to build the project with npm run build. Once I'd done that, pm2 worked as desired.

Express JS code doesnt work with pm2, but when started manually ("node ."/"node index.js")

I got a Discord JS project running which works fine, now I wanted to also run a simple express script to receive a post request. When I do "node ." the code works and successfully logs the requests, if I do "pm2 start index.js --name xyz" the code also starts, logs its boot up message, doesn't shut down, but also doesn't react to any requests. There is simply no response at the set port by express.
Running on an Ubuntu VPS.
Works if I do "pm2 start index.js --name xyz -- --port XXXX" I don't know why and would like to know how these extra arguments work if anyone could explain.
You can read about arguments on the official docs
It's likely you have a runtime error. Please read your own logger files and ~/.pm2/logs/*.log and see if you can find anything. Had it been a syntax error, it would have shut down immediately. Yet, always pm2 statusafter start to double check it.

NodeJS app (Keystone JS) runs fine when started manually, restarts over and over when started with pm2

I am using Ubuntu 16.04 x 64 and I'm running into an issue -
When I run my Keystone JS app manually by typing in "node keystone", the app runs fine and I can view it in my browser like normal.
However, when I start the app using pm2, the app fails immediately and restarts consecutively.
I think it is because keystonejs has a known "error" that is not a real error, but just a warning when it starts.
From the "keystone-out-0.log" file -
Error ...node_modules/bson/build/Release/bson.node: invalid ELF header
However, in the "keystone-error-0.log" file, it gives me a different error that does not occur when I run it manually -
Error: ENOENT: no such file or directory, open '.env'
Any one faced anything similar?
Thanks

Running meteor.js application on your own server

I am trying to run my meteor application on my local network so that when I am off-line I can still use the application on any devices connected to my network. I have been following http://ox86.tumblr.com/post/45184656062/running-your-meteor-js-application-on-your-own-server as a basic tutorial on how to do this. I am new to mongodb and node.js, which causes some trouble. However it seems that everything is working except I do not know where my app is running or what the address is? For example after I complete step 4 from the tutorial
export PORT=8080
export MONGO_URL=mongodb://bill:123456#localhost:27017/dbName
after navigating inside my bundle where main.js is I use
forever start main.js
There are no errors, but I don't know where my app is or if it is even working. Once again I am new to this idea of hosting my own meteor app. Any ideas or suggestions of what I am doing wrong. Also an explanation of the process would be much appreciated. Thanks for the help!
It's likely you have errors. You should check with forever logs main.js to see what you get.
From what it looks like you may have missed the ROOT_URL variable too.
export ROOT_URL=http://www.yoururl.com
export PORT=8080
export MONGO_URL=mongodb://bill:123456#localhost:27017/dbName
forever start main.js
The best check would be to see what you get in the forever logs. Also you may have to install fibers (before you start your app) if you have some error in your logs like invalid ELF header
cd bundle/programs/server/node_modules
rm -r fibers
npm install fibers#1.0.1

Flow of Work Working With Node.JS HTTP server

Learning Node.JS at the moment.
Everything is going fine, just that i have a little challenge with the flow of work.
So i create an HTTP server that listens at a particular port. For example
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
It works fine. Only problem is that when i edit the file that has the above code, and try to start the node process again by typing node server.js i get the following error:
Error: EADDRINUSE, Address already in use.
So i learnt I need to kill the node process using ps before the changes can be reflected and before i can restart.
But this looks like a pain. Do i need to kill the node process anytime i make changes to the server i am writing?
I am sure there is a better way. Any help?
During development I tend to just run node from the command line in a terminal window. When I'm finished with the testing I just Ctrl-C to interrupt the current process which kills node and then press arrow-up enter to restart the process.
my solution is as simple as
npm install dev -g
node-dev app.js
node-dev is the same as 'node' but automatically reruns app.js everytime any file in application dir (or subdir) is changed. it means restarting when static files are changed, too, but should be acceptable for development mode
There isn't any easy way. Authors of node do not like hot-reloading idea, so this is the way it works.
You can hack it if you put your server in a module, require it from the main script, fs.watchFile the .js for changes and then manually stop it as a reaction to a file change, manually deleting it from the module cache (require.cache if I am not mistaken), and require it again.
Or run it in child process and kill and respawn it after a file change (that is, doing automatically what you now do by hand).
You can use something like nodemon (video tutorial about it here) or node-supervisor so that the server auto-restarts when editing files.
If you want to manually do this, then just interrupt the process (CTRL+C) and re-run last command (node server.js).

Resources