NodeJS怎么读写一个JSON文件

NodeJS怎么读写一个JSON文件

1.使用fs读写

const fs = require('fs');

// 读取JSON文件
fs.readFile('data.json', 'utf8', (err, data) => {
    
    
    if (err) {
    
    
        console.error('读取文件时出错:', err);
        return;
    }

    // 将读取到的数据解析为JSON对象
    const jsonData = JSON.parse(data);
    console.log('读取到的JSON数据:', jsonData);

    // 修改JSON数据
    jsonData.newKey = 'newValue';

    // 将修改后的JSON对象转换回字符串
    const newJsonData = JSON.stringify(jsonData, null, 2); // 第二个参数为null,第三个参数为缩进空格数,用于美化输出

    // 写入JSON文件
    fs.writeFile('data_modified.json', newJsonData, (err) => {
    
    
        if (err) {
    
    
            console.error('写入文件时出错:', err);
            return;
        }
        console.log('文件已成功写入!');
    });
});

在上面的代码中,我们首先使用fs.readFile方法读取名为data.json的文件。然后,我们使用JSON.parse方法将读取到的数据解析为一个JavaScript对象。接下来,我们修改该对象,并使用JSON.stringify方法将其转换回一个格式化的JSON字符串。最后,我们使用fs.writeFile方法将修改后的JSON数据写入一个新的文data_modified.json。
在这里插入图片描述
在这里插入图片描述

2.使用Node.js内置的require

const config = require('./require_data.json'); // 直接引入JSON文件,返回的是JavaScript对象
console.log(config);
config.newKey="newValue"

猜你喜欢

转载自blog.csdn.net/fageaaa/article/details/146624342
今日推荐