如何在node.js中创建命名管道?

wak*_*ako 29 pipe named-pipes node.js

如何在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);
    }
});
Run Code Online (Sandbox Code Playgroud)

bef*_*fzz 33

在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');
})
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

关于管道名称的说明:

C/C++/Nodejs:
\\.\pipe\PIPENAME CreateNamedPipe

.Net/Powershell:
\\.\PIPENAME NamedPipeClientStream/NamedPipeServerStream

两者都将使用文件句柄:
\Device\NamedPipe\PIPENAME

  • @NiCkNewman:Windows(NT)命名管道与Unix域套接字高度类似,是的.它们有一些差异(单独的文件系统命名空间,使用IO的文件API和它们自己的API用于管理而不是使用套接字API,当服务器进程消失时不要持久,传递HANDLE与传递fd不同,Windows管道*可以*如果你启用它,可以通过网络访问),但用例几乎相同.保护Windows管道可能很棘手,但可能.Unix(命名)管道/ FIFO更受限制(单向,不能支持多个客户端等) (2认同)

jpi*_*ora 29

看起来名称管道不是也不会在Node核心中得到支持 - 来自Ben Noordhuis 10/11/11:

Windows有一个命名管道的概念,但是你提到mkfifo我假设你的意思是UNIX FIFO.

我们不支持它们,也许永远不会支持(非阻塞模式下的FIFO可能会使事件循环死锁)但是如果需要类似的功能,可以使用UNIX套接字.

https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ

命名管道和插座非常相似然而,net模块通过指定实现本地套接字path,而不是一个hostport:

例:

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();
Run Code Online (Sandbox Code Playgroud)