簡體   English   中英

如何在node.js中的http.request中導出塊

[英]How to export chunk in http.request in node.js

此http.request代碼來自http://nodejs.org/docs/v0.4.7/api/http.html#http.request 如何在res.on中導出

  var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

我不確定“導出”是什么意思,但也許您想將響應的內容放入本地文本文件中?

您可以按照以下步驟進行操作:

var http = require('http');
var fs = require('fs');

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    var response;
    if(fs.existsSync('response.html'))
      response = fs.readFileSync('response.html') + chunk;
    else
      response = chunk;
    fs.writeFileSync('response.html', response);
  });
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

請注意,在觸發每個data事件之后,我們將使用fs.existsSync檢查現有文件,並fs.existsSync填充響應變量,然后使用fs.writeFileSync將響應再次寫入文件。

這在服務器上用處不大,因為文件讀/寫的同步特性將成為您流量的瓶頸,但是它的確突出了響應事件和連接塊的一般概念。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM