首页 > 解决方案 > 如何从作为 Windows 服务运行的 Nodejs 调用函数

问题描述

我已经使用 node-windows 包从 nodeJs 应用程序创建了 windows 服务。下面是我的代码。

主.js

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'SNMPCollector',
  description: 'SNMP collector',
  script: './app.js',
  nodeOptions: [
    '--harmony',
    '--max_old_space_size=4096'
  ]
  //, workingDirectory: '...'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

/* svc.uninstall(); */

应用程序.js

const { workerData, parentPort, isMainThread, Worker } = require('worker_threads')


var NodesList = ["xxxxxxx", "xxxxxxx"]

module.exports.run = function (Nodes) {
  if (isMainThread) {
    while (Nodes.length > 0) {

    // my logic

      })
    }
  }
}

现在,当我运行 main.js 时,它会创建一个 Windows 服务,我可以看到该服务在 services.msc 中运行

但是,如何从任何外部应用程序调用运行服务内部的这个 run() 方法?我找不到任何解决方案,任何帮助都会很棒。

标签: javascriptnode.jswindows-servicesnode-windows

解决方案


您可能会考虑简单地将您的函数导入您run需要的地方并在那里运行它,然后就不需要 Windows 服务,或者main.js- 这假设“任何外部应用程序”是一个 Node 应用程序。

在您的其他应用程序中,您执行以下操作:

const app = require('<path to App.js>');
app.run(someNodes)

对于更广泛的用途,或者如果您确实需要将其作为服务运行,您可以在 App.js 中使用调用您的run函数的端点启动 express(或另一个 Web 服务器)。然后,您需要从其他任何地方对该端点进行 http 调用。

应用程序.js

const express = require('express')
const bodyParser = require('body-parser')
const { workerData, parentPort, isMainThread, Worker } = require('worker_threads')
const app = express()
const port = 3000

var NodesList = ["xxxxxxx", "xxxxxxx"]

const run = function (Nodes) {
  if (isMainThread) {
    while (Nodes.length > 0) {

    // my logic

      })
    }
  }
}

app.use(bodyParser.json())

app.post('/', (req, res) => res.send(run(req.body)))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

(基于 express 的示例 - https://expressjs.com/en/starter/hello-world.html

您需要$ npm install --save express body-parser从 App.js 目录安装 express 和 body-parser:。

从您的其他应用程序中,您需要http://localhost:3000使用 POST 请求和NodesJSON 数组调用端点。


推荐阅读