nodejs starts the node command to run as a windows service (used by node-windows)

foreword

When windows executes the node command, sometimes js needs to do a continuous transaction. When starting with cmd, the window must be kept from being closed. This is definitely not a foolproof solution. At this time, we can try to start the node command to run as a windows service.

Dependency package

Import node-windows dependencies in the project root directory.

npm i node-windows

install service

Suppose I have a file here database.js, what it does is keep writing data to the databasenode database , it will keep running if we need to start it in cmd , and I can't close it for it to function.

We only write one now service.js, and we can install it to run as a windows service.

//service.js

import path from "path";
import nodeWindow from "node-windows";
const Service = nodeWindow.Service;

let svc = new Service({
    
    
  name: "node_database", //名称
  description: "添加数据进入数据库", //描述
  script: path.resolve("./database.js"), //node执行入口文件
  nodeOptions: ["--harmony", "--max_old_space_size=4096"],
});

svc.on("install", function () {
    
    
  svc.start();
  if(svc.exists){
    
    
    console.log('服务安装成功')
  }
});

svc.install();

Then execute the file to run once with node, and execute the installation to end.

node service.js
服务安装成功

insert image description here

uninstall service

//uninstall.js

import path from 'path'
import nodeWindow from 'node-windows'
const Service = nodeWindow.Service

let svc = new Service({
    
    
    name: 'node_database', //名称
    script: path.resolve('./index.js'), //node执行入口文件
    nodeOptions: [
        '--harmony',
        '--max_old_space_size=4096'
    ]
});

svc.on('uninstall', function () {
    
    
    if (!svc.exists) {
    
    
        console.log('服务卸载完成');
    }
});

svc.uninstall();

The same can be started to uninstall the service

node uninstall.js
服务安装成功

Remember to uninstall the installation service when you modify the relevant content .

end words

If you think the article is not bad, please like and collect it. If you have any mistakes or suggestions, you can leave a message. Thank you~

Guess you like

Origin blog.csdn.net/weixin_43877799/article/details/123351572
Recommended