EN
Node.js - write buffer into process.stdout using fs.writeSync() function (sync writing)
5
points
In this short article, we would like to show a simple way how to write data into process.stdout using fs.writeSync() function in Node.js.
Quick solution:
const fs = require('fs'); // or: require('node:fs')
const buffer = Buffer.from("Some text ...");
const count = fs.writeSync(process.stdout.fd, buffer, 0, buffer.length);
Where:
buffercontains bytes to write intoprocess.stdout,writeSync()writes allbufferbytes (starting from0index inbuffer),countcontains number of written bytes (it may be less thanbuffer.length).
Practical example
In this section you can find simple reusable function that lets to write exact number of bytes into process.stdout.
Example index.js file:
const fs = require('fs'); // or: require('node:fs')
const writeBytes = (fd, buffer) => {
for (let i = 0; i < buffer.length;) {
i += fs.writeSync(fd, buffer, i, buffer.length - i);
}
// fs.fdatasyncSync(fd); // used only for some case (you can consider also: fs.fsyncSync())
};
// Usage example:
const buffer = Buffer.from('Some text ...');
writeBytes(process.stdout.fd, buffer); // writes buffer bytes to stdout
Running:
node ./index.js
Output:
Some text ...