用node.js模块向数组添加对象

1.先在文件夹里创建一个JSON文件,里面有一个数组,数组里面有两个对象

2.再创建一个js文件,再js文件里面书写内容,通过node模块向数组里面添加一个对象

//思路
//1.读出这个文件,读出来之后是字符串格式的
//2.JSON.parse(JSON字符串格式)==>数组
//3.数组.push()
//4. 重新写回去-转回字符串
//5.覆盖写入

//引用核心模块fs,path
const fs = require('fs')
const path = require('path')

//拼接绝对路径
const content1 = path.join(__dirname, 'data.json')

//1.读出这个文件,读出来之后是字符串格式的
const content2 = fs.readFileSync(content1, 'utf-8')

//2.JSON.parse(JSON字符串格式)==>数组
const arr = JSON.parse(content2)
// console.log(typeof arr);

//3.数组.push()
arr.push({ "name": "小张" })
// console.log(arr);

//4. 重新写回去-转回字符串
const content3 = JSON.stringify(arr)
// console.log(content3);

//5.覆盖写入
fs.writeFileSync(content1, content3)  //content1是文件地址的绝对路径    content3是内容

3.最后得到效果就是这样:

猜你喜欢

转载自blog.csdn.net/m0_67296095/article/details/124412022