这感觉就像一个显而易见的问题,但令我困惑的是:我想要一个在URI下载资源的Node函数。我需要它来处理几种不同的内容类型,而无需用户指定它是什么类型。
我知道当你知道它将是一个图像时如何将request
传递给fs.createWriteStream
,但是当你已经从请求中调用了回调时,我知道如何处理它。我就在这里:
var request = require('request'),
fs = require('graceful-fs');
function cacheURI(uri, cache_path, cb) {
request(uri, function(err, resp, body) {
var content_type = resp.headers['content-type'].toLowerCase().split("; ")[0],
type = content_type.split("/")[0],
sub_type = content_type.split("/")[1];
if (sub_type == "json") {
body = JSON.parse(body);
}
if (type == "image") {
// this is where the trouble starts
var ws = fs.createWriteStream(cache_path);
ws.write(body);
ws.on('close', function() {
console.log('image done');
console.log(resp.socket.bytesRead);
ws.end();
cb()
});
} else {
// this works fine for text resources
fs.writeFile(cache_path, body, cb);
}
});
}
This answer对上一个问题提出以下建议:
request.get({url: 'https://someurl/somefile.torrent', encoding: 'binary'}, function (err, response, body) {
fs.writeFile("/tmp/test.torrent", body, 'binary', function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
});
});
但如果我还不知道我会得到的回应类型,我就无法将“二进制”传递给request
。
更新
根据建议的答案,在事件处理程序中将“close”更改为“finish”会触发回调:
if (opts.image) {
var ws = fs.createWriteStream(opts.path);
ws.on('finish', function() {
console.log('image done');
console.log(resp.socket.bytesRead);
});
//tried as buffer as well
//ws.write(new Buffer(body));
ws.write(body);
ws.end();
}
这会写入图像文件,但不正确:
答案 0 :(得分:0)
根据here的建议,尝试使用finish
事件(如果您有节点> = v0.10)
ws.on('finish', function() {
console.log('image done');
console.log(resp.socket.bytesRead);
ws.end();
cb()
});