gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:45:52 24 4
gpt4 key购买 nike

我已经使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com