我正在使用socket.io-stream库在2个节点服务器之间传输文件。
服务器A :(发送文件)
var clientIO = require('socket.io-client');
var ss = require('socket.io-stream');
var clientSocket= clientIO(`http://ServerB_Address`);
clientSocket.on('error', (error) => {
console.log(error);
});
var stream = ss.createStream({objectMode: true});
ss(clientSocket).emit('send-file', stream, data);
var uploadedBytes = 0;
var from = 0;
var reader = fs.createReadStream(filePath, {start: from});
reader.pipe(stream)
.on('error', (error) => {
console.log(error);
})
.on('data', (chunk) => {
uploadedBytes += Buffer.byteLength(chunk);
});
服务器B :(接收文件)
var fs = require('fs');
var io = require('socket.io')(http);
var ss = require('socket.io-stream');
io.on('connection', (socket) => {
// listen to send file
ss(socket).on('send-mail', (stream, data) => {
console.log(`*** Begin receive file`);
var writer = fs.createWriteStream(downloadPath, {flags: 'a'});
stream.pipe(writer);
var size = 0;
stream.on('data', (chunk) => {
size += chunk.length;
console.log(`*** Receive ${size} from mail`);
});
stream.on('end', () => {
console.log(`*** End file`);
});
stream.on('error', (error) => {
console.log(`*** Error when receiving file`);
console.log(error);
});
});
});
它工作正常,但是在传输文件时,如果第二个节点服务器已停止,则另一台服务器中的应用程序崩溃并且引发了未处理的错误事件
请任何人告诉我如何捕获此错误?如果有更好的方法在节点服务器之间传输文件?