0

我正在尝试使用 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.
        });
    });
}
4

1 回答 1

1

data可以多次调用该事件。您需要等到所有数据都被写入。

response.setEncoding('utf8');
response.on('data', function (chunk) {
    out.write(chunk);
});
response.on('end', function(){
    out.end();
    var theModule = require(__dirname + "/" + filename);
});

此外,如docscreateClient中所述,已弃用。我还建议使用来简化您的逻辑。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);
  });
}
于 2013-01-01T20:17:44.450 回答