node.js - nodejs throw er;//未处理的 'error'事件

标签 node.js cmd

我做了以下内容,来玩一下node.js。 zipfiles 文件夹中的文件已相应压缩,并且一切似乎都正常。 但我在 cmd 上遇到错误,我不知道它来自哪里,也不知道如何解决。

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: write after end
    at writeAfterEnd (_stream_writable.js:130:12)
    at Gzip.Writable.write (_stream_writable.js:178:5)
    at write (_stream_readable.js:583:24)
    at flow (_stream_readable.js:592:7)
    at ReadStream.pipeOnReadable (_stream_readable.js:624:5)
    at ReadStream.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:408:10)
    at emitReadable (_stream_readable.js:404:5)
    at readableAddChunk (_stream_readable.js:165:9)
    at ReadStream.Readable.push (_stream_readable.js:127:10)

这是我的脚本:

var zlib = require('zlib');
var gzip = zlib.createGzip();
var fs = require('fs');
var zip = {
    zipAll: function(dir){  
        //files to zip
        fs.readdir(dir, function(err, data){
            if(err) throw(err);
            var arrayValue = data.toString().split(',');

            //files with .gz at the end, needs to be excluded
                for(var i=0; i<arrayValue.length; i+=1){
                    console.log("Zipping following files: " + arrayValue[i]);
                    var input = fs.createReadStream('zipfiles/' + arrayValue[i]);
                    var output = fs.createWriteStream('zipfiles/input'+[i]+'.txt'+'.gz');
                    input.pipe(gzip).pipe(output);                  
                } 
        });
    }
};
zip.zipAll('zipfiles');

谢谢

最佳答案

Gzip 对象对于多个文件的重用来说有点不稳定(据我所知没有文档记录)。解决问题的最简单方法是简单地为每个文件使用单独的 gzip 对象进行压缩,例如;

for(var i=0; i<arrayValue.length; i+=1){
    console.log("Zipping following files: " + arrayValue[i]);
    var input = fs.createReadStream('zipfiles/' + arrayValue[i]);
    var output = fs.createWriteStream('zipfiles/input'+[i]+'.txt'+'.gz');
    input.pipe(zlib.createGzip()).pipe(output);                  
} 

关于node.js - nodejs throw er;//未处理的 'error'事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18518264/

相关文章:

node.js - 使用 html 表单数据进行发布时的 Firebase 函数路由问题

node.js - npm publish 是否执行 npm 包

javascript - 无法运行此 DEBUG=AATT* http_port=3000 Node app.js

windows - 检查远程主机上某个端口的状态

r - 使用任务计划程序自动化 Rscript; R 脚本未运行

node.js - 在 Node js 中连接到 postgres 时出错

node.js - 是否有可与 CouchDB 配合使用的基于 NodeJS 的全文搜索索引器(如 Lucene)?

python - 如何在 python 中执行批处理文件后关闭命令提示符窗口?

windows - C++11 std::cout << "string literal in UTF-8"到 Windows cmd 控制台? ( Visual Studio 2015)

bash - 如何从 git bash 使用命令行 Visual Studio 编译器?