新人求助:我通过微信接口获取客户发送的大图片(HTTP流通过data事件分批发送),为啥用fs.appendFile经常发生图片花的情况?
同一张图片当多个data的数据同时写入这个文件的时候,图片就会花掉
resHttps.on('data', function (body) {
fs.appendFile(filePath, body, "utf8", function (err) {
是不是要用同步才行?
去掉就可以?
fs.appendFile(filename, data, encoding=’utf8’, [callback])# Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer. The encoding argument is ignored if data is a buffer.
Example:
fs.appendFile('message.txt’, 'data to append’, function (err) { if (err) throw err; console.log(‘The “data to append” was appended to file!’); });
@xuhaijinsky2008 试试fs.createWriteStream(path, [options])
http://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
例如
http.get(options, function(resp){
console.log(resp.statusCode);
if (resp.statusCode !== 200) {
console.log('failed to get ' + file_url);
return;
}
resp.pipe(fs.createWriteStream(path.join(baseDir, filename)));
console.log(filename);
}).on('error', function(err) {
console.log(err.message);
});
fs.appendFile
不能保证数据按调用顺序添加到文件里。测试代码(不知道为什么执行这段代码会报错……):
var fs = require('fs');
for (var i = 0; i < 10000; i++) {
fs.appendFile('/tmp/appendTest', i % 10);
if (i % 10 == 9) {
fs.appendFile('/tmp/appendTest', '\n');
}
}
cat /tmp/appendTest
结果中出现:
...
0123456789
0123456789
012345679
0123456789
01234567898
0123456789
0123456789
...