4
votes

I am just started learning streams, I am trying to write the number to newfile.txt but it throws a error:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number

The code

const {Readable,pipeline} = require('stream');
const {createWriteStream} = require('fs');

async function myfunc(){
    const stream = Readable.from(Array.from({length:20},(x,i)=>i+1));
    pipeline(stream,createWriteStream('./newfile.txt'),(err)=>{
        console.log(err);
    })
}

myfunc();
1

1 Answers

1
votes

pipeline expects the first argument to be of type ReadableStream. Readable.from returns value of type internal.Readable (not the required readable stream type), that is why you see the error.

Here is an example of how you would use it (loading file as a readable stream and then pushing it to write stream).

const { pipeline } = require('stream');
const { createWriteStream, createReadStream } = require('fs');

async function myfunc() {
    const stream = createReadStream('./oldfile.txt');
    pipeline(stream, createWriteStream('./newfile.txt'), (err) => {
        console.log(err);
    });
}

myfunc();

If you want to push some string (or an object) into a writable stream using pipeline instead of loading contents of some file, you can create readable stream using Duplex

const { Duplex, pipeline } = require('stream');
const { createWriteStream } = require('fs');

const b = Buffer.from('some text');
const readStream = Duplex();
readStream.push(b);
readStream.push(null);

pipeline(readStream, createWriteStream('./newfile.txt'), (err) => {
    console.log(err);
});