How to chain write stream, immediately with a read stream in Node.js 0.10?

前端 未结 3 962
自闭症患者
自闭症患者 2020-12-17 17:37

The following line will download an image file from a specified url variable:

var filename = path.join(__dirname, url.replace(/^.*[\\\\\\/]/, \'         


        
相关标签:
3条回答
  • 2020-12-17 17:40
    // create 'fs' module variable
    var fs = require("fs");
    
    // open the streams
    var readerStream = fs.createReadStream('inputfile.txt');
    var writerStream = fs.createWriteStream('outputfile.txt');
    
    // pipe the read and write operations
    // read input file and write data to output file
    readerStream.pipe(writerStream);
    
    0 讨论(0)
  • 2020-12-17 17:47

    I think the confusion in chaining the pipes is caused by the fact that the pipe method implicitly "makes choices" on it's own on what to return. That is:

    readableStream.pipe(writableStream) // Returns writable stream
    readableStream.pipe(duplexStream) // Returns readable stream
    

    But the general rule says that "You can only pipe a Writable Stream to a Readable Stream." In other words only Readable Streams have the pipe() method.

    0 讨论(0)
  • 2020-12-17 17:58
    request(url).pipe(fs.createWriteStream(filename)).pipe(writestream);
    

    is the same as this:

    var fileStream = fs.createWriteStream(filename);
    request(url).pipe(fileStream);
    fileStream.pipe(writestream);
    

    So the issue is that you are attempting to .pipe one WriteStream into another WriteStream.

    0 讨论(0)
提交回复
热议问题