IT

Node.js를 사용하여 JSON 파일로 데이터 쓰기 / 추가

lottoking 2020. 5. 28. 08:16
반응형

Node.js를 사용하여 JSON 파일로 데이터 쓰기 / 추가


루프 데이터의 노드를 사용하여 JSON 파일을 작성하려고합니다.

let jsonFile = require('jsonfile');

for (i = 0; i < 11; i++) {
    jsonFile.writeFile('loop.json', "id :" + i + " square :" + i * i);
}

loop.json의 outPut은 다음과 같습니다.

id :1 square : 1

그러나 다음과 같은 출력 파일을 원하고 해당 코드를 다시 실행하면 동일한 기존 JSON 파일의 요소로 새로운 출력을 추가해야합니다

{
   "table":[
      {
         "Id ":1,
         "square ":1
      },
      {
         "Id ":2,
         "square ":3
      },
      {
         "Id ":3,
         "square ":9
      },
      {
         "Id ":4,
         "square ":16
      },
      {
         "Id ":5,
         "square ":25
      },
      {
         "Id ":6,
         "square ":36
      },
      {
         "Id ":7,
         "square ":49
      },
      {
         "Id ":8,
         "square ":64
      },
      {
         "Id ":9,
         "square ":81
      },
      {
         "Id ":10,
         "square ":100
      }
   ]
}

첫 번째로 만든 동일한 파일을 사용하고 싶지만 해당 코드를 실행할 때마다 새 요소가 동일한 파일에 추가되어야합니다.

const fs = require('fs');

let obj = {
    table: []
};

fs.exists('myjsonfile.json', function(exists) {

    if (exists) {

        console.log("yes file exists");

        fs.readFile('myjsonfile.json', function readFileCallback(err, data) {

            if (err) {
                console.log(err);
            } else {
                obj = JSON.parse(data);

                for (i = 0; i < 5; i++) {
                    obj.table.push({
                        id: i,
                        square: i * i
                    });
                }

                let json = JSON.stringify(obj);
                fs.writeFile('myjsonfile.json', json);
            }
        });
    } else {

        console.log("file not exists");

        for (i = 0; i < 5; i++) {
            obj.table.push({
                id: i,
                square: i * i
            });
        }

        let json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
    }
});

이 json 파일이 시간이 지남에 따라 너무 커지지 않으면 다음을 시도해야합니다.

  1. 테이블 배열이 포함 된 자바 스크립트 객체를 만듭니다.

    var obj = {
       table: []
    };
    
  2. 그것에 같은 데이터를 추가하십시오

    obj.table.push({id: 1, square:2});
    
  3. stringify를 사용하여 객체에서 문자열로 변환

    var json = JSON.stringify(obj);
    
  4. fs를 사용하여 파일을 디스크에 기록

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. 추가하려면 json 파일을 읽고 객체로 다시 변환하십시오.

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

이것은 최대 100MB의 데이터에 효과적입니다. 이 한계를 초과하면 데이터베이스 엔진을 사용해야합니다.

최신 정보:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.


Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.


you should read the file, every time you want to add a new property to the json, and then add the the new properties

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})

Above example is also correct, but i provide simple example:

var fs = require("fs");
var sampleObject = {
    name: 'pankaj',
    member: 'stack',
    type: {
        x: 11,
        y: 22
    }
};

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log("File has been created");
});

For formatting jsonfile gives spaces option which you can pass as a parameter:

   jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
         console.error(err);
   })

Or use jsonfile.spaces = 4. Read details here.

I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.

var jsonfile = require('jsonfile');
var obj={
     'table':[]
    };

for (i=0; i <11 ; i++){
       obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
      console.log(err);
});

try

var fs = require("fs");
var sampleObject = { your data };

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {  console.error(err);  return; };
    console.log("File has been created");
});

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));

참고URL : https://stackoverflow.com/questions/36856232/write-add-data-in-json-file-using-node-js

반응형