Writing APIs in Node.js?

时间:2017-05-16 09:16:31

标签: javascript node.js

I like Node.js for several reasons and have suggested my company write part of their APIs using it. However, a few on the team of objected to the idea, stating that it is too risky due to its single-threaded nature. Someone pointed out, for instance, that a single mistake in the code like an uncaught exception can crash the whole system. Can somebody help me respond to this argument?

3 个答案:

答案 0 :(得分:1)

While an uncaught exception can cause the whole system to crash, there are tools such as PM2 and forever that can be used to automatically restart the server on an exception, you can hook into the event system with PM2 to get it do whatever you want - send email etc.

Ideally you should be working to produce stable code, however it is possible that an unforseen exception may occur - for this PM2/forever are key to a stable service.

答案 1 :(得分:0)

Firstly, crashes or errors are not bad. You would definitely want to crash as early and often as possible during development to make a product stable. What makes crashing good is the ability to easily reproduce and investigate it.

I find writing code in a multi-threaded environment more challenging as errors get increasingly difficult to reproduce in proportion to the application size. Check out writing effective tracing and error logging support for such an application and you'd appreciate the simplicity offered by single-threaded programming.

Single threaded nature makes NodeJS better at writing predictable and stable code. And for production, if you don't want to crash all the way to terminal you can easily control that by handling some events.

答案 2 :(得分:-1)

process.on('uncaughtException', function (err) {
  console.log(err);
})

Just add this to your code and your process will not crash when you get an uncaught exception.

And you can use Forever, PM2 or strongloop for automatic restart of your process.