如何提高NodeJS程式的穩定性

來源:互聯網
上載者:User

標籤:function   方法   啟動   run   nodejs   運行   命令   var   ring   

當我們寫了個NodeJS程式的時候,一般用node yourjsfile.js命令啟動該程式。但是如果程式中有東西出錯,這個進程就會退出。我們寫程式不可能保證萬無一失,肯定有些沒有處理的錯誤,這就 讓很多人覺得NodeJS不穩定,容易產生很多故障。 下面我就講講幾種方法增加你的NodeJS程式的穩定性。

1.使用 try{…} catch(error){…} 來執行容易出錯的程式碼片段。比如解析一個外來的json字串等。
2.使用 process.on(‘uncaughtException’, function(err){…}); 來處理未被捕捉的錯誤。
3.試用奶媽進程來啟動你的程式,檢測子進程的退出,然後自動重啟該進程。比如 mother.js :

start();function start(){console.log(‘Mother process is running.‘);var ls = require(‘child_process‘).spawn(‘node‘, [‘yourjsfile.js‘]);ls.stdout.on(‘data‘, function (data){console.log(data.toString());});ls.stderr.on(‘data‘, function (data){console.log(data.toString());});ls.on(‘exit‘, function (code){console.log(‘child process exited with code ‘ + code);delete(ls);setTimeout(start,5000);});}

4.使用 nohup 讓nodejs進程在後台運行。 比如運行”nohup node yourjsfile.js > /dev/null &”

如何提高NodeJS程式的穩定性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.