gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:01:01 37 4
gpt4 key购买 nike

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

附:现在我正在创建一个命名管道,如下所示。但我认为这不是最好的方法

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

最佳答案

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

输出:

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

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

关于node.js - 如何在 node.js 中创建命名管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750041/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com