将base64块写入writestream

时间:2014-03-06 03:30:06

标签: javascript node.js sockets stream base64

我与node.js v0.8建立客户端/服务器套接字连接。客户端将jpg编码为base64字符串并将其发送到服务器。服务器正在接收这些块并将其写入写入流。写入数据后,新图像文件与原始图像文件大小相同,但在尝试打开时显示损坏的消息。我是否在使用base64编码或流写入时出错?

Client.js和Server.js代码段:

//Client sending base64 encoded string from image

var net = require('net');
var fs = require('fs');

var socket = new net.Socket();

socket.connect(3000, '127.0.0.1', function() {

    var stream = fs.createReadStream(__dirname + '/node.jpg', {encoding: 'base64'});

    stream.on('data', function(chunk){
        socket.write(chunk, 'base64');
    });

});


//Server should write base64 string into new image file

var net = require('net');
var fs = require('fs');

var imageFilename = "node-copy.jpg";

var writeStream = fs.createWriteStream(__dirname + '/node-copy.jpg', {flags: 'a',  encoding: 'base64'});    

var server = net.createServer(function(socket){  

  socket.setEncoding('base64');

  socket.on("data", function(chunk){
    writeStream.write(chunk, 'base64');
  });

}).listen(3000, '127.0.0.1');

1 个答案:

答案 0 :(得分:0)

您将每个块编码为一个单独的实体,这是一件错误的事情。

使用像this one这样的流式base64模块。