How to pipe to function in node.js?

2020-07-04 07:37发布

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?

const fs = require('fs')

const fred = q => {
    return q.toUpperCase()
}

fs.createReadStream('input.txt')
    .pipe(fred)
    .pipe(fs.createWriteStream('output.txt'))

Currently the error is:

dest.on is not a function

标签: node.js
2条回答
家丑人穷心不美
2楼-- · 2020-07-04 08:37

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! :)

查看更多
Viruses.
3楼-- · 2020-07-04 08:38

Based on answer from Marco but tidied up:

const fs = require('fs')
const {Transform} = require('stream')

const upperCaseTransform = new Transform({
    transform: (chunk, encoding, done) => {
        const result = chunk.toString().toUpperCase()
        done(null, result)
    }
})

fs.createReadStream('input.txt')
    .pipe(upperCaseTransform)
    .pipe(fs.createWriteStream('output.txt'))
查看更多
登录 后发表回答