createWriteStream vs writeFile? [英] createWriteStream vs writeFile?

查看:473
本文介绍了createWriteStream vs writeFile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个操作的基本区别是什么?

someReadStream.pipe(fs。 createWriteStream('foo.png')) ;

$ v

someReadStream.on('data',function(chunk){blob + = chunk} );
someReadStream.on('end',function(){fs。 writeFile('foo.png',blob)});

当使用请求库进行抓取时,我只能使用前一种方法保存图片(png,bmp)等等,而后者则有相同的gibbersh(二进制)数据,但图片不会渲染。

b
$ b

它们有什么不同?

解决方案

当您在node.js中使用流时你应该更喜欢管道他们。



根据节点文档数据事件发出缓冲区(默认)或字符串(如果设置了编码)。

当您使用文本流时,您可以使用'data'事件来连接所有的数据块。然后你就可以像使用常规字符串一样处理你的数据。



但是当你使用二进制数据时,并不是那么简单,因为你会接收缓冲区。要连接缓冲区,您应该使用特殊方法,如 Buffer.concat 。所以,可以使用这种方式来处理二进制流,但是不值得痛苦。






更新<









code> var buffers = [];
readstrm.on('data',function(chunk){
buffers.push(chunk);
});
readstrm.on('end',function(){
fs.writeFile('foo.png',Buffer.concat(buffers));
});

我无法测试,但它看起来不错。



通过检查文件大小很容易发现问题。


What is the basic difference between these two operations ?

someReadStream.pipe(fs.createWriteStream('foo.png'));

vS

someReadStream.on('data',function(chunk) { blob += chunk } ); someReadStream.on('end', function() { fs.writeFile('foo.png',blob) });

When using request library for scraping , i can save pics(png,bmp) etc.. only with the former method and with the latter one there is same gibbersh(binary) data but image doesnt render .

How are they different ?

解决方案

When you are working with streams in node.js you shall prefer piping them.

According to Node Docs 'data' events emits either buffer (by default) or string (if encoding was set).

When you are working with text streams you can use 'data' event to concatenate all chunks of data together. Then you'll be able to work with your data as with regular string.

But when you working with binary data it's not so simple, because you'll receive buffers. To concatenate buffers you shall use special methods like Buffer.concat. So, it's possible to use such approach for binary streams but it not worth the pain.


Update

If you want to do it hard way, try the following code:

var buffers = [];
readstrm.on('data', function(chunk) {
    buffers.push(chunk);
});
readstrm.on('end', function() {
    fs.writeFile('foo.png', Buffer.concat(buffers));
});

I could't test is, but it looks ok.

It's easy to notice when something went wrong by checking file size.

这篇关于createWriteStream vs writeFile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆