【问题标题】:How to write multiple files using Node.js createReadStream and createWriteStream如何使用 Node.js createReadStream 和 createWriteStream 写入多个文件
【发布时间】:2014-01-09 16:57:53
【问题描述】:

好的,这就是这段代码的总体目标。我正在使用 TinyPNG 的 API 来压缩 png 文件的文件夹。我有一个输入文件夹,其中包含许多名为 filename.png 的文件。此代码将文件名目录读取到数组文件中,然后为这些文件创建读取和写入流,以发送到 API、处理并返回,以便将其写入输出文件夹中的文件。我知道该代码适用于一个文件,但除此之外还会引发 write after end 异常,因为管道在第一个文件之后自动关闭。我尝试将输入和输出设置为数组,但这只会引发另一个异常。

任何关于如何设置多个读取和写入流的提示都非常棒,对每个人都非常有用:)。

当前代码:

var fs = require('fs');
var inputFolder = "input/";
var outputFolder = "output/";
var https = require("https");

var key = "GETYOUROWNFREEONEFROMTINYPNG.ORG";

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var options = require("url").parse("https://api.tinypng.com/shrink");
options.auth = "api:" + key;
options.method = "POST";

console.log("Reading files...");

fs.readdir("./input", function (err, files) {

  if (err) throw err;

  console.log(files.length + " files read...");

  var input;
  var output;
  var request;

      for(var i = 0; i < files.length; i++)
      {
        input = fs.createReadStream(inputFolder + files[i]);
        output = fs.createWriteStream(outputFolder + files[i]);

          request = new https.request(options, function(response) {
            if (response.statusCode === 201) {
              /* Compression was successful, retrieve output from Location header. */
              https.get(response.headers.location, function(response) {
                response.pipe(output);
              });
            } else {
              /* Something went wrong! You can parse the JSON body for details. */
              console.log("Compression failed");
            }
          });

          input.pipe(request);
      }

});

感谢@Wyatt提供的答案,这是供其他人使用的固定文件:

var fs = require('fs');
var inputFolder = "input/";
var outputFolder = "output/";
var https = require("https");

var key = "WotZ46HnxPl_HwpT3uZjtY_0f8fMEiSR";

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var options = require("url").parse("https://api.tinypng.com/shrink");
options.auth = "api:" + key;
options.method = "POST";

console.log("Reading files...");

fs.readdir("./input", function (err, files) {

  if (err) throw err;

  console.log(files.length + " files read...");

  var input, request;

  for(var i = 0; i < files.length; i++){
    input = fs.createReadStream(inputFolder + files[i]);
    request = closureRequest(fs.createWriteStream(outputFolder + files[i]));
    input.pipe(request);
  }

});


function closureRequest(output){
    return new https.request(options, function(response) {
        if (response.statusCode === 201) {
          /* Compression was successful, retrieve output from Location header. */
          https.get(response.headers.location, function(response) {
            response.pipe(output);
          });
        } else {
          /* Something went wrong! You can parse the JSON body for details. */
          console.log("Compression failed");
        }
    });
} 

【问题讨论】:

    标签: javascript node.js compression png pipe


    【解决方案1】:

    您在循环中反复重新分配输出变量,而请求回调试图引用它。您可以捕获闭包中的每个值来解决此问题。

    ...
    
    function closureRequest(output){
        return new https.request(options, function(response) {
            if (response.statusCode === 201) {
              /* Compression was successful, retrieve output from Location header. */
              https.get(response.headers.location, function(response) {
                response.pipe(output);
              });
            } else {
              /* Something went wrong! You can parse the JSON body for details. */
              console.log("Compression failed");
            }
        });
    }
    
    var input
      , request
      ;
    
    for(var i = 0; i < files.length; i++){
        input = fs.createReadStream(inputFolder + files[i]);
        request = closureRequest(fs.createWriteStream(outputFolder + files[i]));
        input.pipe(request);
     }
    

    【讨论】:

    • 以创纪录的速度提供出色的答案。有一个错字(可能是因为你回答得太快了) - 在 for 循环中的行: request = closureRequest(fs.createWriteStream(outputFolder + files[i]); 应该是 request = closureRequest(fs.createWriteStream(outputFolder + files [i])); 你错过了一个括号来关闭closureRequest。谢谢你的回答。
    猜你喜欢
    • 2021-05-05
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2019-07-13
    • 2013-10-17
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多