Adding objects to an array with a node.js module

1. First create a JSON file in the folder, which contains an array, and there are two objects in the array

2. Create another js file, write content in the js file, and add an object to the array through the node module

//思路
//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. The final result is like this:

 

Guess you like

Origin blog.csdn.net/m0_67296095/article/details/124412022