本文介绍了使用node-request和fs Promisified下载映像,Node.js中没有管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在设法成功下载映像,而没有将其传输到fs.这是我已经完成的事情:

I have been struggling to succeed in downloading an image without piping it to fs. Here's what I have accomplished:

var Promise = require('bluebird'),
    fs = Promise.promisifyAll(require('fs')),
    requestAsync = Promise.promisify(require('request'));

function downloadImage(uri, filename){
    return requestAsync(uri)
        .spread(function (response, body) {
            if (response.statusCode != 200) return Promise.resolve();
            return fs.writeFileAsync(filename, body);
        })
       .then(function () { ... })

       // ...
}

有效输入可能是:

downloadImage('http://goo.gl/5FiLfb', 'c:\\thanks.jpg');

我确实认为问题出在body的处理上.我尝试用几种编码将其强制转换为Buffer(new Buffer(body, 'binary')等),但均失败.

I do believe the problem is with the handling of body.I have tried casting it to a Buffer (new Buffer(body, 'binary') etc.) in several encodings, but all failed.

谢谢您的帮助!

推荐答案

您必须告诉request数据是二进制的:

You have to tell request that the data is binary:

requestAsync(uri, { encoding : null })

记录在此处:

因此,如果没有该选项,则主体数据将被解释为UTF-8编码,而不是(并产生无效的JPEG文件).

So without that option, the body data is interpreted as UTF-8 encoded, which it isn't (and yields an invalid JPEG file).

这篇关于使用node-request和fs Promisified下载映像,Node.js中没有管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 23:14