【问题标题】:Pass params while Node app is running在 Node 应用程序运行时传递参数
【发布时间】:2017-11-29 03:51:35
【问题描述】:

有没有办法将参数传递和获取到正在运行的节点应用程序?寻找类似信号但带有自定义参数的东西。

process.on('runX', function (params) {
  console.log('RunX called. Params:' + params);
});

$ passParams nodeAppPID runX param1 param2

我尝试解决的最后一个问题是通过 cron 将参数传递到应用程序中。

【问题讨论】:

  • 是的,给你的应用程序一个在 localhost 上运行的小 REST API。 NodeJS 擅长于此。如果你想要更低级别的东西,试试套接字。
  • @byxor 是的,我在考虑 Rest API。但这似乎有点矫枉过正,我不需要在运行应用程序的机器之外访问。只需要通过 cron 将少量数据传递给应用程序。
  • 你可以使用process.stdin

标签: node.js shell terminal cron system-calls


【解决方案1】:

如 cmets 中所述,有两种解决方案:

  1. 使用process.stdin。但似乎流式写入还有其他问题。
  2. 制作本地服务器并通过 curl 调用它。

第二种解决方案的实用程序类:

class RemoteControl {

    constructor(port) {

        this.prefix = '/remote/';
        this.handlers = [];
        this.initServer(port);
    }

    initServer(port) {
        const http = require('http');
        const self = this;

        const server = http.createServer(function (req, res) {
            self.handleRequest(req.url);
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/plain');
            res.end('');
        });

        server.listen(port, () => {
            console.log(`RemoteControl running at http://localhost:${port}/`);
        });

        this.addCall('ping', function () {
            console.log('Remote ping ok');
        });
    }

    /**
     *
     * @param url {String}
     */
    handleRequest(url) {

        let handlerFound = false;

        for (let index in this.handlers) {
            let handler = this.handlers[index];
            if (url === handler.name) {
                console.log('handler called for ' + url);
                handlerFound = true;
                handler.handler();
                break;
            }
        }

        if (!handlerFound) console.log('handler not found for ' + url);
    }

    /**
     *
     * @param callName {String}
     * @param handler {Function}
     */
    addCall(callName, handler) {
        this.handlers.push(new Handler(this.prefix + callName, handler));
    }
}

class Handler {
    /**
     * @param name {String}
     * @param handler {Function}
     */
    constructor(name, handler) {
        this.name = name;
        this.handler = handler;
    }
}

module.exports = RemoteControl;

客户端代码使用:

const remoteControl = new RemoteControl(6666)
remoteControl.addCall('hello', function(){
  //handle hello call
});

定时任务:

* * * * * curl http://localhost:6666/remote/hello

【讨论】:

    猜你喜欢
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2019-03-26
    • 2011-08-09
    相关资源
    最近更新 更多