Regarding how nodejs writes newlines of data one by one, you can use \r\n, but the operating system is different, and there will be conflicts. To avoid this problem, I found a surefire way, which is to use the os module that comes with node ( os .EOL ):
1. Import module
//引入模块
const fs = require('fs')
const os = require('os')
Two, the core part
//创建一个数组
const list = [
1,2,3,4,5,6,7,8,9,10
]
//将数组中每个数据写入并换行
for(let i = 0; i<list.length;i++){
let item = list[i] + os.EOL //使用os.EOL工具换行
//使用appendFile()将数据累计写入
fs.appendFile('./text.js',item,function(err){
if(err){
console.log('写入失败!')
} else {
console.log('success')
}
})
}
3. Final result
The above is the valuable information in this article, I hope it will be helpful to you!