Languages
[Edit]
EN

Node.js - write buffer into process.stdout using fs.writeSync() function (sync writing)

5 points
Created by:
Majid-Hajibaba
972

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:

  • buffer contains bytes to write into process.stdout,
  • writeSync() writes all buffer bytes (starting from 0 index in buffer),
  • count contains number of written bytes (it may be less than buffer.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 ...

 

See also

  1. Node.js - read process.stdin using fs.readSync() function

References

  1. process.stdout - Node.js API
  2. fs.writeSync() - Node.js API
  3. fs.fsyncSync() - Node.js API
  4. fs.fdatasyncSync() - Node.js API

Alternative titles

  1. Node.js - write buffer into process.stdout using fs.writeSync() method
  2. Node.js - sync write operation into process.stdout
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join