我想更新一个.json文件,请告诉我如何去做


I want to Update a .json file please tell me how to go about it

以下是代码: 我正在编写一个函数来更新文件中json颜色属性。我可以更新对象,但无法将其写回文件(修改文件)。当用户通过表单输入时json我需要更新数据文件。

 function updatecolor(id, color) {
   $.ajax({
     type: "GET",
     dataType: "json",
     url: "Data.json",
     cache: false,
     beforeSend: function() {
       $('#table').html('loading please wait...');
     },
     success: function(jsondata) {
       console.log(jsondata);
       count = jsondata.length;
       for (i = 0; i < jsondata.length; i++) {
         if (jsondata[i].id == id)
           jsondata[i].color = color;

       }
       window.alert(JSON.stringify(jsondata));
     }
   });
 }
 function popupform() {
   $('#formpop').show();
 }
 function my() {
   $.ajax({
     type: "GET",
     dataType: "json",
     url: "Data.json",
     cache: false,
     beforeSend: function() {
       $('#table').html('loading please wait...');
     },
     success: function(jsondata) {
       console.log(jsondata);
       count = jsondata.length;
       var str = '';
       var str2 = '';
       var str3 = '';
       //str += '<ul>';
       $.each(jsondata, function(idx, obj) {
         var match = obj.Color;
         if (match == "Blue") {
           str += 'ID :' + obj.id + '    Color : ' + obj.Color + '<br> ';
         }
       });
       $.each(jsondata, function(idx, obj) {
         var match = obj.Color;
         if (match == "Red") {
           str2 += 'ID :' + obj.id + '    Color : ' + obj.Color + '<br> ';
         }
       });
       $.each(jsondata, function(idx, obj) {
         var match = obj.Color;
         if (match == "Green") {
           str3 += 'ID :' + obj.id + '    Color : ' + obj.Color + '<br> ';
         }
       });
       //str += '</ul>';
       $('#abc').html(str);
       $('#abc2').html(str2);
       $('#abc3').html(str3);
     }
   });
 }

编辑 - 从注释部分在此处添加服务器代码:

var http = require("http"); 
var fs = require("fs"); 
function send404Response(response){ 
  response.writeHead(404, {"Content-Type": "text/plain"}); 
  response.write("Error 404 - Page not found"); 
  response.end(); 
} 
function onRequest(request, response) { 
  if( request.method == 'GET' && request.url == '/' ){ 
    response.writeHead(200, {"Content-Type": "text/html"}); //Open file as readable stream, pipe stream to response object 
    fs.createReadStream("./index.html").pipe(response);
  }else{
    send404Response(response); 
  } 
} 
http.createServer(onRequest).listen(8888);

https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

Node.js 包括用于将数据写入文件的函数。使用fs.writeFile()写入所需的文件。请注意,如果文件已存在,它将替换该文件。

还有一个fs.write()函数,看起来您可以追加到现有函数的末尾。