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

后端 未结 8 2225
-上瘾入骨i
-上瘾入骨i 2020-11-28 00:27

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

8条回答
  •  情话喂你
    2020-11-28 00:49

    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.

提交回复
热议问题