How to Print to Console Without Trailing Newline in Node.js

To print to the console without adding a trailing newline, you can use the “process.stdout.write()” method.

Example 1: Printing multiple strings on the same line

process.stdout.write("First string, ");
process.stdout.write("second string, ");
process.stdout.write("and third string.");

Output

First string, second string, and third string.

Example 2: Displaying a counter without a new line

This example will display a counter that updates on the same line, giving the appearance of an “in-place” update.

const delay = 1000;

for (let i = 1; i <= 5; i++) {
  process.stdout.write(`Counting: ${i} \r`);
  // Sleep for a while
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay);
}

console.log("\nDone counting.");

Output

Counting: 5
Done counting.

To add a new line after printing a string, you can use the process.stdout.write() function with the \n escape sequence, or you can use the console.log() method.

process.stdout.write('This is Sparta!\n');

Output

This is Sparta!

Example 3: Add trailing newline to the output

In Node.js, the console.log() method is used to add a trailing newline to the output by default.

console.log("Pathaan! ");
console.log("This is Jawaan");

Output

Pathaan!
This is Jawaan

That’s it!

Leave a Comment