美文网首页
node.js 实现windows服务

node.js 实现windows服务

作者: Hi小胡 | 来源:发表于2019-04-12 16:46 被阅读0次

1. 安装node-windows

npm install node-windows --save

2. 在项目根目录新建三个文件

  • index.js
var http = require('http');
var obj = {
    id: "123",
    name: "hester"
}
http.createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": 'text/plain', 'charset': 'utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS' });//可以解决跨域的请求
    res.write(JSON.stringify(obj));
    res.end();
}).listen(8060, function () {
    console.log('http://localhost:8060')
});
  • nw-install.js (安装服务)
let Service = require('node-windows').Service;

let svc = new Service({
    name: 'node_test',    //服务名称
    description: 'node_test', //描述
    script: './index.js' //nodejs项目要启动的文件路径
});

svc.on('install', () => {
    svc.start();
});

svc.install();
  • nw-uninstall.js (卸载服务)
let Service = require('node-windows').Service;

let svc = new Service({
    name: 'node_test',    //服务名称
    description: 'node_test', //描述
    script: './index.js' //nodejs项目要启动的文件路径
});

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

svc.uninstall();

3. 执行命令

node nw-install.js //安装服务
node nw-uninstall.js //卸载服务

4. 运行效果

相关文章

网友评论

      本文标题:node.js 实现windows服务

      本文链接:https://www.haomeiwen.com/subject/swzcwqtx.html