ProgramingTip

json 파일의 값을 업데이트하고 node.js를 통해 저장하는 방법

bestdevel 2020. 11. 30. 19:24
반응형

json 파일의 값을 업데이트하고 node.js를 통해 저장하는 방법


json 파일의 값을 업데이트하고 node.js를 통해 저장 비용을 부담해야합니까? 파일 내용이 있습니다.

var file_content = fs.readFileSync(filename);
var content = JSON.parse(file_content);
var val1 = content.val1;

이제 값을 변경 val1하여 파일에 저장 하고 싶습니다 .


자신이 스스로 수행하는 것입니다. 같은 차단이 우려되는 경우 특히 유용합니다.

var fs = require('fs');
var fileName = './file.json';
var file = require(fileName);

file.key = "new value";

fs.writeFile(fileName, JSON.stringify(file), function (err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

주의 할 점은 json이 파일에 한 줄로 작성되고 예쁘지 않다는 것입니다. 전의 :

{
  "key": "value"
}

될거야 ...

{"key": "value"}

방지 고려 다음 두 개의 추가 인수를 JSON.stringify

JSON.stringify(file, null, 2)

null-대체 기능을 나타냅니다. (이 경우 우리는 프로세스를 변경하고 싶지 않습니다)

2 -들여 쓰기 할 공백을 나타냅니다.


//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));

참고 URL : https://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js

반응형