如何在node.js中创建命名管道?
P.S .: 现在我正在创建一个命名管道,如下所示。但我认为这不是最好的方式
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);
}
});
答案 0 :(得分:30)
节点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
答案 1 :(得分:28)
看起来名称管道不在节点核心中支持 - 来自Ben Noordhuis 10/11/11:
Windows有一个命名管道的概念,但是你提到
mkfifo
我 假设您的意思是UNIX FIFO。我们不支持它们,也许永远不会支持它们(非阻塞的FIFO) 模式有可能使事件循环死锁)但你可以使用 UNIX套接字,如果您需要类似的功能。
https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ
命名管道和套接字非常相似,但net
模块通过指定path
而不是host
和port
来实现本地套接字:
示例:
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();
答案 2 :(得分:0)
也许使用fs.watchFile
而不是命名管道?见documentation