javascript - 如何从作为 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() 方法?我找不到任何解决方案,任何帮助都会很棒。
解决方案
您可能会考虑简单地将您的函数导入您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 请求和Nodes
JSON 数组调用端点。
推荐阅读
- charts - 如何避免谷歌条形图中的重叠注释?
- angular - 是否可以从组件/指令中修改 ng-content
- java - Azure FileShare:指定的资源不存在 - SAS 身份验证
- android - Android:使用camera2录制视频时出错
- python - 如何将一系列条件应用于 np.where()
- google-api - 将“Google 我的商家”评论嵌入网页
- mysql - mysql - 在一个查询中为同一个表选择两个条件的结果
- c++ - 保存用户输入的文件名 c++
- ef-core-2.2 - EFCORE 2.2.6 简单连接抛出 必须是可约节点
- ms-access - 如何创建一个使用方程式对另一个表中的数据进行平均的表?