How to pipe to function in node.js?

前端 未结 3 1171
余生分开走
余生分开走 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:24

    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'))
    

提交回复
热议问题