简体   繁体   中英

How to insert a line break in js?

im creating a bot for my discord server and am attempting to log messages onto a text file. I stored all the information i need about the message in a var named logger and am attempting to use node to append my log file.

I tried adding \\n to the end of the variable but kept getting a syntax error that pointed to the "\\" and said invalid or unexpected token

var logger = (message.author.username + "> " + message.content \n)
fs.appendFile('msgs.json', logger, (err) => {
    if (err) throw err;
})

I would like each entry to be on a different line

new-line are characters that need to be concatenated onto the end of the string

var logger = (message.author.username + "> " + message.content + "\n")
fs.appendFile('msgs.json', logger, (err) => {
    if (err) throw err;
})

Here you go, you need to quote the \\n , either using double quote, single quote, or `

var logger = (message.author.username + "> " + message.content + "\n")
fs.appendFile('msgs.json', logger, (err) => {
    if (err) throw err;
})

Looks like you are using Windows machine. 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 (eg Wordpad).

Use:

var logger = (message.author.username + "> " + message.content + '\r\n')
fs.appendFile('msgs.json', logger, (err) => {
    if (err) throw err;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM