我正在尝试使用node.js编写自己的文件共享器应用程序。我写了发件人代码和接收者代码。发送文本文件时工作正常,但尝试发送.jpg或.mp3等文件时失败。问题出在接收端,文件被收到“损坏”。以下是我的发件人代码和收件人代码
发信人:
const net = require('net');
const fs = require('fs');
var destAddr = process.argv[2],
destPort = process.argv[3],
sourceFile = process.argv[4];
const client = net.connect(destPort, destAddr, function() {
/*fs.readFile(sourceFile,function(err,data){
if(data)
{
if(client.write(data)==true)
{
console.log("Data [ size: %d ] written succesfully",data.length);
client.destroy();
}
else console.log("Data write failure");
}
else
client.write("err");
});
*/
var fileStream = fs.createReadStream(sourceFile);
fileStream.on('error', function(err) {
console.log(err);
});
fileStream.on('open', function() {
fileStream.pipe(client);
});
});
接收器:
const net = require('net');
const fs = require('fs');
var fileName = 'receivedfile.' + process.argv[2];
// process.argv[2] is the file extension to be used to write the file to disk at the receiving end;
const options = {
allowHalfOpen: false,
pauseOnConnect: false,
};
var fileCount = 0;
const server = net.createServer(options, function(listener) {
listener.on('data', (data) => {
console.log("Data [ size: %d ] received", data.length);
fs.writeFile(fileName, data, function(err) {
if (err) console.log("Error writing file to disk");
else {
console.log("Write successful");
fileCount++;
console.log("[ Files received =] %d", fileCount);
console.log("Press Ctr+c to exit");
}
});
});
}).listen(8001, () => {
console.log("Client is waiting for the file on port 8001");
});
我哪里错了?
答案 0 :(得分:2)
data
事件可以在连接的生命周期内多次触发,具有各种大小的数据块。
相反,使用流可能更容易:
const server = net.createServer(listener => {
let stream = fs.createWriteStream(fileName);
listener.on('error', err => console.log('socket error', err));
stream .on('error', err => console.log('file error', err));
listener.pipe(stream).on('finish', () => {
console.log("Write successful");
fileCount++;
console.log("[ Files received =] %d", fileCount);
console.log("Press Ctr+c to exit");
})
}).listen(...);