听外面的事件。 Bash到NodeJS桥 [英] Listening for outside events. Bash to NodeJS bridge

查看:72
本文介绍了听外面的事件。 Bash到NodeJS桥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NodeJS流程中,如何从bash中侦听事件?

Being inside of a NodeJS process, how can I listen for events from bash?

例如

NodeJS

obj.on("something", function (data) {
   console.log(data);
});

Bash

$ do-something 'Hello World'

然后在NodeJS标准输出中将出现Hello World消息。

Then in the NodeJS stdout will appear "Hello World" message.

我该怎么做?

我想这与信号事件<有关/ a>。

I guess it's related to signal events.

推荐答案

使用信号的问题是你不能传递参数,而且大多数是为系统保留的已经使用(我认为 SIGUSR2 实际上是唯一安全的节点,因为 SIGUSR1 启动调试器并且这些是唯一的两个应该是用户定义的条件。)

The problem with using signals is that you can't pass arguments and most of them are reserved for system use already (I think SIGUSR2 is really the only safe one for node since SIGUSR1 starts the debugger and those are the only two that are supposed to be for user-defined conditions).

相反,我发现这样做的最好方法是使用 UNIX套接字;它们是为进程间通信而设计的。

Instead, the best way that I've found to do this is by using UNIX sockets; they're designed for inter process communication.

在节点中设置UNIX套接字的最简单方法是使用 net.createServer() 然后只需将文件路径传递给 server.listen() 在您指定的路径上创建套接字。 注意:重要的是该路径上的文件不存在,否则您将收到 EADDRINUSE 错误。

The easiest way to setup a UNIX socket in node is by setting up a standard net server with net.createServer() and then simply passing a file path to server.listen() to create the socket at the path you specified. Note: It's important that a file at that path doesn't exist, otherwise you'll get a EADDRINUSE error.

这样的事情:

var net = require('net');

var server = net.createServer(function(connection) {
    connection.on('data', function(data) {
        // data is a Buffer, so we'll .toString() it for this example
        console.log(data.toString());
    });
});

// This creates a UNIX socket in the current directory named "nodejs_bridge.sock"
server.listen('nodejs_bridge.sock');

// Make sure we close the server when the process exits so the file it created is removed
process.on('exit', function() {
    server.close();
});

// Call process.exit() explicitly on ctl-c so that we actually get that event
process.on('SIGINT', function() {
    process.exit();
});

// Resume stdin so that we don't just exit immediately
process.stdin.resume();

然后,要实际在bash中向该套接字发送内容,可以输入 nc 喜欢这样:

Then, to actually send something to that socket in bash, you can pipe to nc like this:

echo "Hello World" | nc -U nodejs_bridge.sock

这篇关于听外面的事件。 Bash到NodeJS桥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆