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:
xxxxxxxxxx
1
const fs = require('fs'); // or: require('node:fs')
2
3
const buffer = Buffer.allocUnsafe(1024);
4
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.
In this section you can find simple reusable function that lets to read exact number of bytes from process.stdin
.
xxxxxxxxxx
1
const fs = require('fs'); // or: require('node:fs')
2
3
const readBytes = (fd, count) => {
4
const buffer = Buffer.allocUnsafe(count);
5
for (let i = 0; i < count;) {
6
let result = 0;
7
try {
8
result = fs.readSync(fd, buffer, i, count - i);
9
} catch (error) {
10
if (error.code === 'EAGAIN') { // when there is nothing to read at the current time (Unix)
11
//TODO: it is good to slow down loop here or do other tasks in meantime, e.g. async sleep
12
continue;
13
}
14
throw error;
15
}
16
if (result === 0) {
17
throw new Error('Input stream reading error.'); // consider to use your own solution on this case
18
}
19
i += result;
20
}
21
return buffer;
22
};
23
24
25
// Usage example:
26
27
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.
In this section, you can fund unified version that works the same way under Window and Unix/Linux.
xxxxxxxxxx
1
const fs = require('fs');
2
3
// Reads bytes into buffer returning -1 when transmission ended.
4
//
5
const readSync = (fd, buffer, offset, length) => {
6
try {
7
const result = fs.readSync(fd, buffer, offset, length);
8
return result === 0 ? -1 : result;
9
} catch (error) {
10
if (error.code === 'EAGAIN') { // when there is nothing to read at the current time
11
return 0;
12
}
13
throw error;
14
}
15
};