Nodejs file write and export operations – get the local JSON file and export the specified format JSON

Time:2021-7-30

Export and write jnos files:
Through the FS operation file built in nodejs, get the local JSON data, traverse and format to generate new JSON data, and export it to the local

var fs = require('fs'); // File module
var path = require('path'); // System path module

//Get local JSON file
var file = path.join(__dirname, 'src/path.json');
var allArr=[];
//Read JSON file
fs.readFile(file, 'utf-8', function(err, data) {
if (err) {
    Res.send ('File reading failed ');
} else {
    var newData=JSON.parse(data);
    //Format data
    for(let j=0;j<newData.length;j++){
        let list=[];
        var index=j*2;
        if(newData[index]){
            list.push(newData[index]);
            list.push(newData[index+1]);
            allArr.push(list);
        }
    }

    
    var content = JSON.stringify(allArr); 

    //Specify the creation directory and file name__ Dirname is the directory where the current JS file is executed
    var file = path.join(__dirname, 'json/path.json'); 

    //Write file
    fs.writeFile(file, content, function(err) {
        if (err) {
            return console.log(err);
        }
        Console.log ('File created successfully, address: '+ file);
    });
}});

Path.json data:
[

113.24253,23.17111,113.24288,23.17116,113.24297,23.17149,113.24243,23.17140,113.24227,23.17101,113.24205,23.17111,113.24189,23.17048

]

Generate a new JSON file:
[[113.24253,23.17111],[113.24288,23.17116],[113.24297,23.17149],[113.24243,23.1714],[113.24227,23.17101],[113.24205,23.17111],[113.24189,23.17048]]