Nodo.js: ¿imprimir en la consola sin una nueva línea final?


¿Existe un método para imprimir en la consola sin una nueva línea final? La documentación del objeto console no dice nada con respecto a eso:

console.log()

Imprime en stdout con nueva línea. Esta función puede tomar múltiples argumentos de una manera similar a printf(). Ejemplo:

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

Si los elementos de formato no se encuentran en la primera cadena, se usa util.inspect en cada argumento.

Author: Evan Carroll, 2011-05-28

8 answers

Puedes usar process.stdout.write():

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

Ver los documentos para más detalles.

 807
Author: onteria_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-30 20:15:45

También, si desea sobrescribir mensajes en la misma línea, por ejemplo en una cuenta atrás, puede agregar '\r' al final de la cadena.

process.stdout.write("Downloading " + data.length + " bytes\r");
 316
Author: rodowi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-09 04:26:57

En la consola de Windows (Linux, también), debe reemplazar '\r' con su código equivalente \033[0G :

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

Esto usa una secuencia de escape de terminal VT220 para enviar el cursor a la primera columna.

 15
Author: Yan Te,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-15 03:12:00

Útil.print también se puede utilizar. Léase: http://nodejs.org/api/util.html#util_util_print

Útil.imprimir([...])# Una función de salida síncrona. Bloqueará el proceso, emitirá cada argumento a una cadena y luego la salida estándar. No coloca nuevas líneas después de cada argumento.

Un ejemplo:

// 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");
});
 13
Author: douyw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-15 13:02:43

Parece que hay muchas respuestas que sugieren process.stdout.write. Los registros de errores deben emitirse en process.stderr en su lugar (Use console.error). Para cualquiera que se pregunte por qué proceso.stdout.write ('\033[0G'); no estaba haciendo nada es porque stdout está en búfer y necesita esperar a drain evento (Ver Stdout flush para NodeJS?). Si write devuelve false se disparará un evento drain.

 7
Author: Ahmed Masud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

Como una expansión/mejora de la brillante adición hecha por @rodowi anteriormente con respecto a ser capaz de sobrescribir una fila:

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

Si no desea que el cursor de la terminal esté ubicado en el primer carácter, como vi en mi código, considere hacer lo siguiente:

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)

Al colocar el \r delante de la siguiente instrucción print, el cursor se restablece justo antes de que la cadena de reemplazo sobrescriba la anterior.

 4
Author: mraxus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-27 00:33:06

Ninguna de estas soluciones funciona para mí. proceso.stdout.write ('ok\033[0G') y simplemente usando '\r ' simplemente cree una nueva línea, no sobrescriba, Mac OSX 10.9.2

EDITAR: Tuve que usar esto para reemplazar la línea actual

Proceso.stdout.escribir ('\033[0G'); proceso.stdout.('newstuff');

 3
Author: Tyguy7,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-04 18:44:51

Recibí un error al usar el modo estricto.

Error de nodo: "Los literales octales no están permitidos en modo estricto."

Encontré la respuesta aquí: https://github.com/SBoudrias/Inquirer.js/issues/111

Proceso.stdout.write ("received:" + BytesReceived + "\x1B[0G");

 3
Author: blablabla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-30 08:48:47