EN
Node.js - read process.stdin using fs.readSync() function (sync reading)
8
points
In this short article, we would like to show a simple way how to read data from process.stdin
using fs.readSync()
function in Node.js.
Quick solution:
const fs = require('fs'); // or: require('node:fs')
const buffer = Buffer.allocUnsafe(1024);
const count = fs.readSync(process.stdin.fd, buffer, 0, buffer.length);
Where:
buffer
contains read bytes fromprocess.stdin
,readSync()
reads bytes and puts them tobuffer
starting from0
index inbuffer
,count
contains number of read bytes.
Practical example
In this section you can find simple reusable function that lets to read exact number of bytes from process.stdin
.
const fs = require('fs'); // or: require('node:fs')
const readBytes = (fd, count) => {
const buffer = Buffer.allocUnsafe(count);
for (let i = 0; i < count;) {
let result = 0;
try {
result = fs.readSync(fd, buffer, i, count - i);
} catch (error) {
if (error.code === 'EAGAIN') { // when there is nothing to read at the current time (Unix)
//TODO: it is good to slow down loop here or do other tasks in meantime, e.g. async sleep
continue;
}
throw error;
}
if (result === 0) {
throw new Error('Input stream reading error.'); // consider to use your own solution on this case
}
i += result;
}
return buffer;
};
// Usage example:
const buffer = readBytes(process.stdin.fd, 1024); // waits for bytes in stdin and reads them into buffer
Hint: consider to use async API or standard input events.
Legacy version
In this section, you can fund unified version that works the same way under Window and Unix/Linux.
const fs = require('fs');
// Reads bytes into buffer returning -1 when transmission ended.
//
const readSync = (fd, buffer, offset, length) => {
try {
const result = fs.readSync(fd, buffer, offset, length);
return result === 0 ? -1 : result;
} catch (error) {
if (error.code === 'EAGAIN') { // when there is nothing to read at the current time
return 0;
}
throw error;
}
};