How to pipe to function in node.js?

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

    Using async iteration is the cleaner new way to transform streams:

    const fs = require('fs');
    (async () => {
        const out = fs.createWriteStream('output.txt');
        for await (const chunk of fs.createReadStream('input.txt', 'utf8')) {
            out.write(chunk.toUpperCase());
        }
    })();
    

    As you can see, this way is a lot more terse and readable if you already are working in an async function context.

提交回复
热议问题