Greetings. I'm trying to get data from the stream.

process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { let chunk = String(process.stdin.read()); console.log(chunk); }); 

I'm coming back

 Input: 10 2 Your output: 10 2 null 

How to get rid of null?

    2 answers 2

    Alternatively, check that process.stdin.read() returned something useful (not null ).

    Naturally, you need to check before the cast to the line, and not after. Like that:

     process.stdin.on('readable', () => { var chunk = process.stdin.read(); if (!chunk) { return; } chunk = "" + chunk; console.log(chunk); }); 
    • @DmitriySimushev, well, so I output to the console that this is true. I did not understand what was wrong. - Qwertiy
    • @DmitriySimushev, can be more detailed comments. As far as I understand, process.stdin.read() returned null (itself null, not a string, not a buffer, but null), it ran it without checking to the string "null" and outputted it. I am wrong? - Qwertiy
    • @DmitriySimushev, so you need to check before the cast, and not after. I wrote that you need to compare the process.stdin.read() with null , and not the chunk with "null" . - Qwertiy
    • @DmitriySimushev, clarified the answer. - Qwertiy
    • @DmitriySimushev, minus something you remove? - Qwertiy

    Why is this happening?

    The readable event is thrown not only when a new piece of data is available, but also when the end of the stream is reached:

    Here is what is said in the official documentation :

    This is a "readable" event.

    Further, if you try to read from the stream after the end of the stream has been reached, the stream.read method will return null .

    Let me quote the documentation again:

    Note: Calling stream.read([size]) after the 'end' event has been returned. No runtime error will be raised.

    In other words, a null return is the regular behavior of a readable stream.


    What to do?

    There are several options here:

    1. The stream.read method returns null only one case. You can explicitly check the result of stream.read for this value:

       process.stdin.on('readable', () => { let chunk = process.stdin.read(); if (null !== chunk) { console.log(chunk.toString()); } }); 
    2. You can use the stream in a different ( flowing ) mode and receive data on the data event:

       process.stdin.on('data', (chunk) => { console.log(chunk.toString()); }); 
    • Hmm .. and in the second case, provided that he used setEncoding wouldn't the chunk be a string right away? - Qwertiy
    • It will be, as well as in the first. On the other hand, in the answer I do not use setEncoding , so conversion to a string is necessary - Dmitriy Simushev
    • <s> Then why bring? </ s> Ok. - Qwertiy