繁体   English   中英

如何从作为 windows 服务运行的 Nodejs 调用 function

[英]How to call function from Nodejs running as windows service

我使用 node-windows package 从 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 function 导入您需要的地方并在那里运行它,然后就不需要 windows 服务或main.js - 这假设“任何外部应用程序”是一个节点应用程序。

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

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

对于更广泛的用途,或者如果您确实需要将其作为服务运行,您可以在 App.js 中使用调用您的run function 的端点启动 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}`))

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

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

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

您可以像其他答案提到的那样在端口上公开它,但您需要确保不会根据您运行的环境更广泛地公开它。 这里有一个关于确保端口被锁定的好答案下。

作为在端口上公开它的替代方法,您可以通过在任何其他应用程序中运行命令来简单地调用 function:

node -e 'require("/somePathToYourJS/app").run()'

一个问题是 app.js 现在将以调用应用程序拥有的任何权限运行。 虽然这可以通过运行runas来解决。 更多细节在这里 但是一个例子是:

runas /user:domainname\username "node -e 'require(^"/somePathToYourJS/app^").run()'"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM