如何创建node.js的命名管道?
PS:现在我创建一个命名管道,如下所示。 但我认为这不是最好的方法
var mkfifoProcess = spawn('mkfifo', [fifoFilePath]);
mkfifoProcess.on('exit', function (code) {
if (code == 0) {
console.log('fifo created: ' + fifoFilePath);
} else {
console.log('fail to create fifo with code: ' + code);
}
});
貌似名管不得,也不会在节点核心支持 - 从本Noordhuis 10/11/11:
Windows有命名管道的概念,但既然你提到mkfifo
我假定你的意思是UNIX的FIFO。
我们不支持他们,可能永远也不会(在非阻塞模式的FIFO有死锁事件循环的可能性),但如果你需要类似的功能,你可以使用Unix套接字。
https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ
命名管道和套接字非常相似然而, net
模块实现通过指定一个本地套接字path
,而不是一个host
和port
:
- http://nodejs.org/api/net.html#net_server_listen_path_callback
- http://nodejs.org/api/net.html#net_net_connect_path_connectlistener
例:
var net = require('net');
var server = net.createServer(function(stream) {
stream.on('data', function(c) {
console.log('data:', c.toString());
});
stream.on('end', function() {
server.close();
});
});
server.listen('/tmp/test.sock');
var stream = net.connect('/tmp/test.sock');
stream.write('hello');
stream.end();
在Windows命名管道工作
节点v0.12.4
var net = require('net');
var PIPE_NAME = "mypipe";
var PIPE_PATH = "\\\\.\\pipe\\" + PIPE_NAME;
var L = console.log;
var server = net.createServer(function(stream) {
L('Server: on connection')
stream.on('data', function(c) {
L('Server: on data:', c.toString());
});
stream.on('end', function() {
L('Server: on end')
server.close();
});
stream.write('Take it easy!');
});
server.on('close',function(){
L('Server: on close');
})
server.listen(PIPE_PATH,function(){
L('Server: on listening');
})
// == Client part == //
var client = net.connect(PIPE_PATH, function() {
L('Client: on connection');
})
client.on('data', function(data) {
L('Client: on data:', data.toString());
client.end('Thanks!');
});
client.on('end', function() {
L('Client: on end');
})
输出:
Server: on listening
Client: on connection
Server: on connection
Client: on data: Take it easy!
Server: on data: Thanks!
Client: on end
Server: on end
Server: on close
请注意有关管道名称:
C / C ++ /的NodeJS:
\\.\pipe\PIPENAME
CreateNamedPipe时
.NET / PowerShell的:
\\.\PIPENAME
NamedPipeClientStream / NamedPipeServerStream
双方将使用文件句柄:
\Device\NamedPipe\PIPENAME
也许使用fs.watchFile
而不是命名管道? 见文档