1

在 Node.js 中,我使用下面的代码从服务器下载文件。API调用成功。我将“数据”以“二进制”编码保存到本地文件后,相应软件无法打开本地文件。我比较了本地文件和服务器文件的文件大小。有一个小的区别。

我找不到我错的地方。OAuth 库是否支持文件下载?

var OAuth = require('oauth').OAuth;

var consumer = new OAuth('',
            null,
            consumer_key, consumer_key_secret, '1.0',
            null, 'HMAC-SHA1');

consumer.get(url
        , oauth_token, ooauth_token_secret
        , function (err, data, response){
            var filename = path.join(__dirname, "test.dwg");
            var file = fs.createWriteStream(filename);

            console.log('Data length: ' + data.length);

            file.write(data, 'binary', function(err){                       
                console.log('Complete');
            });             
        }       
    );
4

1 回答 1

0

I got the solution after some testing.

The reason of this issue is we are receiving the http body in 'utf8' encoding. Use the 'binary' encoding can fix it.

The oauth module only supports the utf8 encoding when get the response. This is hard code in file "oatuh\lib\oauth.js" at "Line # 375, response.setEncoding('utf8');".

Even though I set the encoding as the code below. It still doesn't work. So this module can't be used to download binary files.

var consumer = new OAuth('',
            null,
            consumer_key, consumer_secret, '1.0',
            null, 'HMAC-SHA1', 32, {encoding: "binary"});

Solution: Use the request module to download the file. The code is as below.

var oauth = {
    consumer_key: consumer_key
    , consumer_secret: consumer_secret
    , token: token
    , token_secret: token_secret
};
request.get({url:url, oauth:oauth, encoding: "binary"}, function(err, res, body){..});
于 2012-12-19T06:35:13.143 回答