javascript - 如何从作为 Windows 服务运行的 Nodejs 调用函数

标签 javascript node.js windows-services node-windows

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

主程序

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() 方法?我找不到任何解决方案,任何帮助都会很棒。

最佳答案

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

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

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

对于更广泛的使用,或者如果您确实需要将其作为服务运行,您可以在 App.js 中启动一个 express(或另一个网络服务器),并使用一个端点来调用您的 run功能。然后,您需要从其他任何地方对该端点进行 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 )

你需要安装 express 和 body-parser:$ npm install --save express body-parser来自 App.js 的目录。

从您的其他应用程序中,您需要调用端点 http://localhost:3000带有 POST 请求和 Nodes作为 JSON 数组。

关于javascript - 如何从作为 Windows 服务运行的 Nodejs 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61114221/

相关文章:

javascript - 从 Ext JS 面板渲染 Kendo 菜单

c#-4.0 - 启用 Topshelf 的 Windows 服务将无法调试

node.js - app.use() 需要中间件函数 app.use( seneca.export ('web' ) );

node.js - 在 sequelize 中的 destroy() 中没有清理多对多关系

javascript - 按子对象属性值对对象属性进行排序

c# - 在 Windows 服务上设置恢复选项

windows-services - 删除没有EXE的Windows服务

javascript - 如何在 Vanilla JS 的特定字符之前保留字符串中的所有字母?

javascript - 将函数 A 作为 prop 传递,并在子函数调用 A 时调用另一个函数

javascript - $.getJSON() 不适用于 chrome