Home > Web Front-end > JS Tutorial > How to read and write json files in nodejs? Method introduction

How to read and write json files in nodejs? Method introduction

青灯夜游
Release: 2021-02-01 11:23:37
forward
2412 people have browsed it

How does nodejs read and write json files? The following article will introduce to you how to read and write json files in nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to read and write json files in nodejs? Method introduction

Related recommendations: "nodejs tutorial"

Reading json files

'use strict';

const fs = require('fs');

let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);

写json文件:
'use strict';

const fs = require('fs');

let student = { 
    name: 'Mike',
    age: 23, 
    gender: 'Male',
    department: 'English',
    car: 'Honda' 
};
 
let data = JSON.stringify(student);
fs.writeFileSync('student-2.json', data);
Copy after login

Although this is what we want The data is written, but the data is in the form of a one-line string, which is difficult for us to read.
If you want the serialized JSON to be human readable, then change the JSON. Stringify function:
let data = JSON.stringify(student, null, 2);

json to csv

// require json-2-csv module
const converter = require('json-2-csv');
const fs = require('fs');

// read JSON from a file
const todos = JSON.parse(fs.readFileSync('todos.json'));

// convert JSON array to CSV string
(async () => {
    try {
        const csv = await converter.json2csvAsync(todos);

        // print CSV string
        console.log(csv);

        // write CSV to a file
        fs.writeFileSync('todos.csv', csv);

    } catch (err) {
        console.log(err);
    }
})();
Copy after login

csv to json

csv第一行为key,例如:  id,name,email,country,age
// require csvtojson module
const CSVToJSON = require('csvtojson');

// convert users.csv file to JSON array
(async () => {
    try {
        const users = await CSVToJSON().fromFile('users.csv');

        // log the JSON array
        console.log(users);

    } catch (err) {
        console.log(err);
    }
})();
Copy after login

More For programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How to read and write json files in nodejs? Method introduction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template