?txt文件
?
?
const fs = require('fs')
const path = require('path')
const p = path.join(__dirname, 'a.txt')
fs.readFile(p, 'utf8', (err, data) => {
if (err) {
console.log('错误', err)
return
}
let arr = data.split('\r\n')
// console.log(arr)
let num = 0
let sum = 0
let arrs = []
arr.forEach(item => {
let obj = {}
// console.log(item.split(',')[0])
obj.name = item.split(',')[0]
obj.age = item.split(',')[1]
// console.log(obj.age)
arrs.push(obj)
// 总和
sum += +obj.age
// console.log(sum)
num++
})
// console.log(arrs)
let json = {
list: arrs,
average: sum / num,
total: num
}
// console.log(json)
fs.writeFile(path.join(__dirname, 'b.json'), JSON.stringify(json), (err) => {
console.log('err', err)
})
})
json文件
?
|