Difference Between process.stdout.write and console.log

In Node.js, both process.stdout.write and console.log are used to output data to the terminal, but they serve different purposes and behave differently. This article explains the key differences between these two methods, focusing on automatic formatting, newline handling, accepted data types, and their ideal use cases.

1. Newline Characters (\n)

The most immediate visual difference between the two methods is how they handle line breaks.

// Using console.log
console.log("Hello");
console.log("World");
// Output:
// Hello
// World

// Using process.stdout.write
process.stdout.write("Hello");
process.stdout.write("World");
// Output:
// HelloWorld

2. Supported Data Types and Formatting

The two methods process inputs and format data differently.

const user = { name: "Alice" };

// This works perfectly
console.log(user); 

// This will throw a TypeError: write after end / Invalid non-string/buffer datum
process.stdout.write(user); 

// To use process.stdout.write, you must manually serialize the data
process.stdout.write(JSON.stringify(user) + "\n");

3. Implementation Under the Hood

The relationship between the two is hierarchical. In Node.js, console.log is actually built on top of process.stdout.write.

When you call console.log("text"), Node.js formats the input, appends a newline character, and then calls process.stdout.write("text\n") internally.

Summary: When to Use Which?