在Node.js中,fs.createFileStream生成的Stream在读取到另一个流之后是不可读的

时间:2012-11-30 02:14:26

标签: node.js stream zipstream

我正在使用node-zipstream在node.js中创建ZIP文件。我创建了一个简单的包装器,以便在向ZIP添加流时创建同步API的错觉(包含在下面的代码中)。

当使用request流时,一切都按预期工作,但是当我使用文件流时,第二个流在第一个流完成后变得不可读。

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

function ZipQueue(out, options) {
    var zip = zipstream.createZip(options);
    zip.pipe(out);

    var queue = new Array();

    this.addFile = function(readStream, options) {
        queue.push({stream: readStream, options: options});
    }
    this.runQueue = function(cb) {
        for(var element in queue) {
            queue[element].stream.on('error', function(err) {
                console.dir(err);
            })
        }
        function run() {
            i++;
            if (queue.length > i) {
                console.log("Queue:");
                console.dir(queue);
                console.log("\n");
                zip.addFile(queue[i].stream, queue[i].options, run);
            }
            else {
                zip.finalize(cb);
            }
        }
        var i = -1;
        run();
    }
}

var out = fs.createWriteStream('out.zip');

var q = new ZipQueue(out, { level: 1 });
q.addFile(fs.createReadStream("1.txt"), { name: 'files/1.txt' });
q.addFile(fs.createReadStream("2.txt"), { name: 'files/2.txt' });
q.runQueue(function(written) { console.log(written + ' total bytes written'); });

控制台输出:

>node zip.js
Queue:
[ { stream:
     { path: '1.txt',
       fd: null,
       readable: true,
       paused: false,
       flags: 'r',
       mode: 438,
       bufferSize: 65536,
       _events: [Object] },
    options: { name: 'files/1.txt' } },
  { stream:
     { path: '2.txt',
       fd: null,
       readable: true,
       paused: false,
       flags: 'r',
       mode: 438,
       bufferSize: 65536,
       _events: [Object] },
    options: { name: 'files/2.txt' } } ]


Queue:
[ { stream:
     { path: '1.txt',
       fd: 4,
       readable: false,
       paused: false,
       flags: 'r',
       mode: 438,
       bufferSize: 65536,
       _events: [Object],
       reading: false },
    options:
     { name: 'files/1.txt',
       version: 20,
       bitflag: 8,
       method: 8,
       moddate: 1098783117,
       offset: 0,
       crc32: -137262718,
       compressed: 7,
       uncompressed: 5 } },
  { stream:
     { path: '2.txt',
       fd: 5,
       readable: false,
       paused: false,
       flags: 'r',
       mode: 438,
       bufferSize: 65536,
       _events: [Object],
       reading: false },
    options: { name: 'files/2.txt' } } ]

0 个答案:

没有答案