How to create a named pipe in node.js?

大兔子大兔子 提交于 2019-11-28 04:09:34

Looks like name pipes aren't and won't be supported in Node core - from Ben Noordhuis 10/11/11:

Windows has a concept of named pipes but since you mention mkfifo I assume you mean UNIX FIFOs.

We don't support them and probably never will (FIFOs in non-blocking mode have the potential to deadlock the event loop) but you can use UNIX sockets if you need similar functionality.

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

Named pipes and sockets are very similar however, the net module implements local sockets by specifying a path as opposed to a host and port:

Example:

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();

Working with named pipes on Windows

Node 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');
})

Output:

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

Note about pipe names:

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

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

Both will use file handle:
\Device\NamedPipe\PIPENAME

Maybe use fs.watchFile instead of named pipe ? See documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!