在windows服務器上使用node-windows部署nodeJS服務

一般部署nodejs的項目,大家都會用到forever這個庫,這個庫相當好用,可以讓nodejs的站點在後臺跑,不需要cmd的窗口一直開着。在windows下,如果用戶一直不註銷,這種方式是可行的,但在服務器上的話就麻煩了,因爲服務器在部署完成後,一般都會註銷,那麼站點就掛了。

因此需要把它部署成windows服務,廢話不多說,部署成windows服務需要幾個步驟。

1. 全局安裝node-windows的庫

npm i -g node-windows

2. 在項目中新建一個安裝文件nw.js 

let path = require('path');
 
let Service = require('node-windows').Service;
 
// Create a new service object
let svc = new Service({
  name:'node windows server test', //名稱
  description: 'The socket.io nodejs server test ',//描述
  script:  path.resolve('./index.js'),//node執行入口
  nodeOptions: [
    '--harmony',
    '--max_old_space_size=4096'
  ]
});
 
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});
 
svc.install();

3.在項目中新建一個卸載文件nw-uninstall.js

// 卸載文件nw-uninstall.js
    let Service = require('node-windows').Service;

    let svc = new Service({
        name:'node windows server test', //名稱
        description: 'The socket.io nodejs server test ',//描述
        script:  path.resolve('./index.js'),//node執行入口
        nodeOptions: [
          '--harmony',
          '--max_old_space_size=4096'
        ]
      });

  svc.on('uninstall',function(){
      console.log('Uninstall complete.');
      console.log('The service exists: ',svc.exists);
    });

  svc.uninstall();

4.執行命令 

node nw.js //安裝服務       
node nw-uninstall //卸載服務

注意:每次修改nw.js文件後,需要重新執行node nw.js

查看服務,已經在運行中了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章