如何在node.js中创build一个命名pipe道?
如何在node.js中创build一个命名pipe道?
PS:现在我正在创build一个命名pipe道,如下所示。 但我认为这不是最好的方法
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); } });
看起来像名字pipe道不是也不会在Node核心支持 – 从本Noordhuis 10/11/11:
Windows有一个命名pipe道的概念,但既然你提到
mkfifo
我假设你的意思是UNIX的FIFO。我们不支持它们,也许永远不会(非阻塞模式下的FIFO有可能导致事件循环死锁),但是如果你需要类似的function,你可以使用UNIX套接字。
https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ
命名pipe道和套接字非常相似,但是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上使用命名pipe道
节点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
关于pipe道名称的说明:
C / C ++ / Nodejs:
\\.\pipe\PIPENAME
CreateNamedPipe.Net / Powershell:
\\.\PIPENAME
NamedPipeClientStream / NamedPipeServerStream两者都将使用文件句柄:
\Device\NamedPipe\PIPENAME
也许使用fs.watchFile
而不是命名pipe道? 见文件