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.
console.log()automatically appends a newline character (\n) to the end of your output. Every time you call it, the cursor moves to the next line.process.stdout.write()does not append a newline character. If you want a line break, you must explicitly include\nin the string.
// 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:
// HelloWorld2. Supported Data Types and Formatting
The two methods process inputs and format data differently.
console.log()is a high-level wrapper. It can accept any data type (objects, arrays, numbers, booleans) and automatically converts them into a readable string format using Node’s internalutil.format()utility. It also supports string formatting placeholders (like%sor%d).process.stdout.write()is a low-level stream method. It only accepts strings or Buffer objects. If you pass an object, number, or array directly to it, Node.js will throw a type error.
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?
- Use
console.logfor standard application logging, quick debugging, and outputting structured data like JSON objects. It is easier to write, safer, and handles formatting automatically. - Use
process.stdout.writewhen you need precise control over the terminal output. This is ideal for building command-line interfaces (CLIs), progress bars, loaders, or when piping raw stream data where automatic newlines would break the output structure.