Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 216
NO WAR WITH RUSSIA Avatar asked May 27 '11 20:05

NO WAR WITH RUSSIA


People also ask

How do you print to the console without a trailing new line?

In that case, we can use process. stdout. write() method to print to console without trailing newline. Note: The process object is global so it can be used without using require() method.

How do I print a new line in node JS?

Try using \r\n instead of just \n . Honestly, \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

Does console log make a new line?

To create a multi line strings when printing to the JavaScript console, you need to add the new line character represented by the \n symbol. Alternatively, you can also add a new line break using Enter when you use the template literals syntax.

How do you break a line in console?

In JavaScript, the \n symbol stands for the newline character. If we need to print words in different lines on the console, we can use \n inside the string to introduce the line break.


2 Answers

You can use process.stdout.write():

process.stdout.write("hello: "); 

See the docs for details.

like image 167
onteria_ Avatar answered Sep 20 '22 08:09

onteria_


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"); 
like image 27
defvol Avatar answered Sep 19 '22 08:09

defvol