Ion*_*zău 3 javascript bash node.js
在NodeJS进程中,我如何从bash中侦听事件?
例如
NodeJS方面
obj.on("something", function (data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
Bash方面
$ do-something 'Hello World'
Run Code Online (Sandbox Code Playgroud)
然后在NodeJS stdout中会出现"Hello World"消息.
我怎样才能做到这一点?
我想这与信号事件有关.
使用信号的问题是你不能传递参数,而且大多数都是为系统使用而保留的(我认为SIGUSR2实际上它是节点的唯一安全的一个,因为它SIGUSR1启动了调试器,而那些只是两个应该是用户定义的条件).
相反,我发现这样做的最好方法是使用UNIX套接字 ; 它们是为进程间通信而设计的.
在节点中设置UNIX套接字的最简单方法是使用设置标准网络服务器,net.createServer()然后简单地传递文件路径以server.listen()在指定的路径上创建套接字.注意:该路径上的文件不存在很重要,否则您将收到EADDRINUSE错误.
像这样的东西:
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();
Run Code Online (Sandbox Code Playgroud)
然后,要实际在bash中向该套接字发送内容,您可以管道nc这样:
echo "Hello World" | nc -U nodejs_bridge.sock
Run Code Online (Sandbox Code Playgroud)
小智 6
使用FIFO怎么样?
NodeJS代码:
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write('data: ' + chunk);
}
});
Run Code Online (Sandbox Code Playgroud)
NodeJS启动(这3>/tmp/...是保持FIFO打开的技巧):
mkfifo /tmp/nodeJsProcess.fifo
node myProgram.js </tmp/nodeJsProcess.fifo 3>/tmp/nodeJsProcess.fifo
Run Code Online (Sandbox Code Playgroud)
Bash链接:
echo Hello >/tmp/nodeJsProcess.fifo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |