node 读取txt文件输出json
通过nodeJS读取本地txt文件,然后输出json文件,支持命令行运行时,传入参数,自定义txt文件名称。
js文件
运行命令 node server [filename] ,filename为要转换txt的文件名。
const fs = require("fs")
const path = require("path")
// node启动命令参数
const arguments = process.argv
// 支持命令行输入参数选择文件
const fileName = arguments[2] ? arguments[2] : 'test'
var arr = []
// 读取txt文件
fs.readFile(`./files/${fileName}.txt`, 'utf-8', (err, data) => {
if (err) console.log(err)
console.log(data)
arr = data.split('\r\n')
//定义输出文件路径
const outputFile = path.join(__dirname, `output/${fileName}.json`)
fs.writeFile(outputFile, JSON.stringify(arr, '' , ' '), (err) => {
if (err) {
console.log(err)
} else {
console.log(`output/${fileName}.json 创建成功!!!`)
}
})
})
txt文件
151
sdsa
555
输出的json
[
"151",
"sdas",
"555"
]
项目目录
txt文件放在files文件夹里,输出的json文件放置在output文件夹里。