Created
September 5, 2013 02:12
-
-
Save leizongmin/6445255 to your computer and use it in GitHub Desktop.
Node.js 读取远程文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
/** | |
* 读取远程文件 | |
* | |
* @param {String} url | |
* @param {Function} cb | |
* - {Error} err | |
* - {Buffer} buf | |
*/ | |
function readRemoteFile (url, cb) { | |
var callback = function () { | |
// 回调函数,避免重复调用 | |
callback = function () {}; | |
cb.apply(null, arguments); | |
}; | |
var req = http.get(url, function (res) { | |
var b = []; | |
res.on('data', function (c) { | |
b.push(c); | |
}); | |
res.on('end', function () { | |
callback(null, Buffer.concat(b)); | |
}); | |
res.on('error', callback); | |
}); | |
req.on('error', callback); | |
} | |
readRemoteFile('http://www.baidu.com/img/bdlogo.gif', function (err, buffer) { | |
if (err) throw err; | |
console.log(buffer.length, buffer); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
请问这个可以直接返回结果吗?现在看来好像结果都在回调函数内,无法传出来