我正在尝试使用node.js脚本下载并要求.js文件,但只下载了部分文件。
具体来说,这是导致问题的部分:
response.on('data', function (chunk) {
out.write(chunk);
var theModule = require(__dirname + "/" + filename);
//less than half of the file is downloaded when the above line is included.
});
以下是完整的源代码:
var http = require('http');
var fs = require('fs');
downloadModule("functionChecker.js");
function downloadModule(filename) {
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/svn/' + filename, {
'host': 'javascript-modules.googlecode.com'
});
request.end();
out = fs.createWriteStream(filename);
request.on('response', function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
out.write(chunk);
var theModule = require(__dirname + "/" + filename);
//less than half of the file is downloaded when the above line is included.
//If the import statement is omitted, then the file is downloaded normally.
});
});
}
答案 0 :(得分:1)
可以多次调用data
事件。您需要等到写完所有数据。
response.setEncoding('utf8');
response.on('data', function (chunk) {
out.write(chunk);
});
response.on('end', function(){
out.end();
var theModule = require(__dirname + "/" + filename);
});
此外,createClient
已被弃用,如the docs中所述。我还建议使用pipe
来简化您的逻辑。
function downloadModule(filename) {
http.get({
hostname: 'javascript-modules.googlecode.com',
path: '/svn/' + filename
}, function(res){
var out = fs.createWriteStream(filename);
out.on('close', function(){
var theModule = require(__dirname + "/" + filename);
});
res.pipe(out);
});
}