【问题标题】:How to call function from Nodejs running as windows service如何从作为 Windows 服务运行的 Nodejs 调用函数
【发布时间】:2020-04-09 04:52:48
【问题描述】:

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

Main.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(); */

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

【问题讨论】:

  • 您可以为它创建一个 CLI。不行吗?
  • 如何创建 cli ?
  • 我无法在评论中解释整个事情。但我强烈推荐这篇文章developer.okta.com/blog/2019/06/18/command-line-app-with-nodejs
  • 您不会创建服务以使用其他脚本/程序按需运行它;服务用于执行某种任务或操作。您可以使用您可能使用的服务创建 HTTP 端点。

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


【解决方案1】:

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

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

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

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

App.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

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

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

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多