使用node-request和fs Promisified下载映像,Node.js中没有管道 [英] Download an image using node-request, and fs Promisified, with no pipe in Node.js

查看:144
本文介绍了使用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 })

记录在此处:

encoding-用于响应数据的setEncoding的编码.如果为null,则将正文作为Buffer返回.其他任何内容(,包括未定义的默认值)都将作为编码参数传递给toString()(这意味着默认情况下它实际上是utf8).

encoding - Encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default).

因此,如果没有该选项,则主体数据将被解释为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中没有管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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