【问题标题】:Decompress streaming response using pipe syntax使用管道语法解压缩流响应
【发布时间】:2017-09-05 19:28:56
【问题描述】:

我正在尝试使用 request.js 检索 file.csv.gz,并在对其进行解析和处理之前对其进行解压缩。

我知道我希望我的代码看起来像这样

response
.pipe(zlib.createGunzip())
.pipe(split())
.pipe(process())

但是,我正在努力让我的响应对象以正确的格式通过管道传输。我目前正在尝试通过以下方式流式传输响应;

const request = require('request');

const headers = {
  'accept-encoding':'gzip'
}

module.exports.getCSV = (url) => {
  return request({url, headers, gzip:true});
}

我收到的错误提示我正在尝试解压缩不完整的对象。

我也认为可能无法实现我想要实现的目标,相反,我需要完全下载文件,然后再尝试对其进行解析以进行处理

【问题讨论】:

  • 我们可以看到文件或链接吗?

标签: node.js stream data-processing


【解决方案1】:

receive.js

const http = require('http');
const fs = require('fs');
const zlib = require('zlib');

const server = http.createServer((req, res) => {
    const filename = req.headers.filename;
    console.log('File request received: ' + filename);
    req
     .pipe(zlib.createGunzip())
     .pipe(fs.createWriteStream(filename))
     .on('finish', () => {
        res.writeHead(201, {'Content-Type': 'text/plain'});
        res.end('Complete\n');
        console.log(`File saved: ${filename}`);
     });
 });
 server.listen(3000, () => console.log('Listening'));

发送.js

const fs = require('fs');
const zlib = require('zlib');
const http = require('http');
const path = require('path');
const file = 'myfile.txt'; //Put your file here
const server = 'localhost'; //Put the server here
const options = {
    hostname: server,
    port: 3000,
    path: '/',
    method: 'PUT',
    headers: {
      filename: path.basename(file),
      'Content-Type': 'application/octet-stream',
      'Content-Encoding': 'gzip'
      }
  };

const req = http.request(options, res => {
   console.log('Server response: ' + res.statusCode);
});
fs.createReadStream(file)
 .pipe(zlib.createGzip())
 .pipe(req)
 .on('finish', () => {
   console.log('File successfully sent');
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多