简体   繁体   English

NodeJS多次向浏览器写入响应

[英]NodeJS write response to browser multiple times

I have a simple nodeJS server that fetches data from another server and store them in a JSON files, i need to write a status about each file fetched and generated, but that doesn't work, because i have to execute response.end(), which implies that i can't write to the stream again, without ending the stream 我有一个简单的nodeJS服务器,该服务器从另一台服务器获取数据并将其存储在JSON文件中,我需要为每个获取和生成的文件写一个状态,但这是行不通的,因为我必须执行response.end() ,这意味着我不能在不结束流的情况下再次写入流

here's my code: 这是我的代码:

      var http = require('http');
  var module = require('fs');
  var APIs = [ '/servlet/en', '/servlet/fr' ];
  var langs =[ 'en', 'fr' ];
  var finish = false;
  var host = 'http://www.localtest';
  const port = process.argv[2] || 9000;
  var responses = [];

  http.createServer(function (req, response) {

    for (x in APIs){
      console.log(x);
    var options = {
      host: 'localtest',
      port: 8888,
      path: APIs[x],
      lang: langs[x]
    };

    http.get(options, function(res) {
        res.setEncoding('utf8');
        var body='';
        res.on('data', function(chunk){
          body += chunk;
        });
        res.on('end', function(chunk){
          responses.push(body);

          if (responses.length == 2){
          var d = JSON.parse(responses[1]);
          var d2 = JSON.parse(responses[0]);

        module.writeFileSync("options.lang1"+".json",JSON.stringify(d) , 'utf-8');
        module.writeFileSync("options.lang2"+".json",JSON.stringify(d2) , 'utf-8');
        }
        });

    });

  }

  }).listen(parseInt(port));

  console.log(`Server listening on port ${port}`);

An example, i tried to write a message to the user after the line : responses.push(body); 例如,我尝试在以下行后向用户写一条消息:response.push(body); using response.write(), but this method needs an response.end() in order to be executed and displayed on the browser, If i do that i can't write to the stream anymore! 使用response.write(),但是此方法需要response.end()才能在浏览器中执行和显示,如果这样做,我将无法再写入流!

Couple issues with your code here. 您的代码在这里有几个问题。 First off, you shouldn't use module as a variable, as that is a word that's already used in node's moduling system, eg in module.exports 首先,您不应该将module用作变量,因为这是已经在节点的module.exports系统中使用的单词,例如在module.exports

Second, You really want to have some control flow in there. 其次,您真的想在其中拥有一些控制流程。 here's a complete example using the async library, though others prefer Promises. 这是一个使用async库的完整示例,尽管其他人更喜欢Promises。

 var http = require('http');
  var fs = require('fs');
  var APIs = [ '/servlet/en', '/servlet/fr' ];
  var langs =[ 'en', 'fr' ];
  var host = 'http://www.localtest';
  const port = process.argv[2] || 9000;

  const async = require('async');
  let responses = [];

  function fetchAndWriteFile(lang, callback){
    var options = {
      host: 'localtest',
      port: 8888,
      path: '/servlet/'+lang,
      lang: lang
    };

    http.get(options, function(res) {
        res.setEncoding('utf8');
        const filename = 'options.'+lang+'.json';
        const fileStream = fs.createWriteStream(filename, {defaultEncoding: 'utf-8'});
        fileStream.on('end', (e)=> {
            if(e) return callback(e);
            return callback(null, filename);
        });

        res.pipe(fileStream)
    });
  }

  http.createServer(function (req, response) {
    // this will run the fetchAndWriteFile once for each lang in langs
    async.map(langs, fetchAndWriteFile, (e, files) => {
        response.end(files); // files will be an array of filenames saved
    });

  }).listen(parseInt(port));

  console.log(`Server listening on port ${port}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM