[node.js] Node.js: printing to console without a trailing newline?

Is there a method for printing to the console without a trailing newline? The console object documentation doesn't say anything regarding that:

console.log()

Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. Example:

console.log('count: %d', count);

If formating elements are not found in the first string then util.inspect is used on each argument.

This question is related to node.js console console.log

The answer is


As an expansion/enhancement to the brilliant addition made by @rodowi above regarding being able to overwrite a row:

process.stdout.write("Downloading " + data.length + " bytes\r");

Should you not want the terminal cursor to be located at the first character, as I saw in my code, the consider doing the following:

let dots = ''
process.stdout.write(`Loading `)

let tmrID = setInterval(() => {
  dots += '.'
  process.stdout.write(`\rLoading ${dots}`)
}, 1000)

setTimeout(() => {
  clearInterval(tmrID)
  console.log(`\rLoaded in [3500 ms]`)
}, 3500)

By placing the \r in front of the next print statement the cursor is reset just before the replacing string overwrites the previous.


I got the following error when using strict mode:

Node error: "Octal literals are not allowed in strict mode."

The following solution works (source):

process.stdout.write("received: " + bytesReceived + "\x1B[0G");

util.print can be used also. Read: http://nodejs.org/api/util.html#util_util_print

util.print([...])# A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

An example:

// get total length
var len = parseInt(response.headers['content-length'], 10);
var cur = 0;

// handle the response
response.on('data', function(chunk) {
  cur += chunk.length;
  util.print("Downloading " + (100.0 * cur / len).toFixed(2) + "% " + cur + " bytes\r");
});

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

There seem to be many answers suggesting:

process.stdout.write

Error logs should be emitted on:

process.stderr

Instead use:

console.error

For anyone who is wonder why process.stdout.write('\033[0G'); wasn't doing anything it's because stdout is buffered and you need to wait for drain event (more info).

If write returns false it will fire a drain event.


In Windows console (Linux, too), you should replace '\r' with its equivalent code \033[0G:

process.stdout.write('ok\033[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.


Also, if you want to overwrite messages in the same line, for instance in a countdown, you could add '\r' at the end of the string.

process.stdout.write("Downloading " + data.length + " bytes\r");

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working

Examples related to console.log

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." Can't access object property, even though it shows up in a console log How can I add a variable to console.log? Printing to the console in Google Apps Script? How can I get the full object in Node.js's console.log(), rather than '[Object]'? Node.js: printing to console without a trailing newline? What is console.log?