How to stop node js server from crashing

I am new to node js. I tried to create a simple HTTP server. I followed the famous example and created "Hello World!" server as follows.

var handleRequest = function(req, res) { res.writeHead(200); res1.end('Hello, World!\n'); }; require('http').createServer(handleRequest).listen(8080); console.log('Server started on port 8080'); 

Running this code will start the server properly, as expected. But an attempt to access http://127.0.0.1:8080 will cause it to fail if you reset an error that is not defined by res1 . I would like the server to continue to work and gracefully report errors whenever it encounters this.

How do I achieve this? I tried trying, but this does not help me :(

+6
source share
3 answers

There are tons of comments here. First of all, for the operation of your sample server, handleRequest must be defined before use.

1- What you really want, which impedes the exit process, can be handled by handling uncaughtException ( documentation ) event:

 var handleRequest = function(req, res) { res.writeHead(200); res1.end('Hello, World!\n'); }; var server = require('http').createServer(handleRequest); process.on('uncaughtException', function(ex) { // do something with exception }); server.listen(8080); console.log('Server started on port 8080'); 

2- I would suggest using try {} catch (e) {} in your code, for example:

 var handleRequest = function(req, res) { try { res.writeHead(200); res1.end('Hello, World!\n'); } catch(e) { res.writeHead(200); res.end('Boo'); } }; 

3- I think the example was just an example, not the actual code, this is a parsing error that can be prevented. I mention this since you MUST have parsing errors in catch Exception handlers.

4. Note that the node process will be replaced in the future domain

5- I would rather use a framework like express than doing this.

6- Recommended lecture: fooobar.com/questions/13145 / ...

+6
source

I am not setting up your questions, but your question is about preventing a Node server crash. You can probably use DOMAIN , this will probably stop your server from crashing when calling uncaughtException.

 domain = require('domain'), d = domain.create(); d.on('error', function(err) { console.error(err); }); 

for more details go to http://shapeshed.com/uncaught-exceptions-in-node/

In addition to this method, you must try to capture your block.

+1
source

You may need to define handleRequest before using it:

 require('http').createServer(handleRequest).listen(8080); function handleRequest(req, res) { res.writeHead(200); res1.end('Hello, World!\n'); }; 

Or

 var handleRequest = function(req, res) { res.writeHead(200); res1.end('Hello, World!\n'); }; require('http').createServer(handleRequest).listen(8080); 

And you must be sure that res1 also exists.

0
source

All Articles