How to pipe to function in node.js?

前端 未结 3 1197
余生分开走
余生分开走 2021-02-19 23:02

I want to read from file to stream, pipe the output to a function that will upperCase the content and then write to file. This is my attempt. What am I doing wrong?



        
3条回答
  •  伪装坚强ぢ
    2021-02-19 23:23

    You have to use Transform if you want to "transform" streams. I recommend you to read: https://community.risingstack.com/the-definitive-guide-to-object-streams-in-node-js/

    const fs = require('fs')
    
    const Transform = require('stream').Transform;
    
      /// Create the transform stream:
      var uppercase = new Transform({
        decodeStrings: false
      });
    
      uppercase._transform = function(chunk, encoding, done) {
        done(null, chunk.toString().toUpperCase());
      };
    
    fs.createReadStream('input.txt')
    .pipe(uppercase)
    .pipe(fs.createWriteStream('output.txt'))
    

    EDIT: You need to call .toString() in chunk because it's a buffer! :)

提交回复
热议问题