如何使用节点js向现有文件添加一些额外数据

我有一个像This这样的文件

  Matching /* Rewrite */  Can be passed on from the environment to the individual. This can be from a person, insects or from the physical environment.  Communicable  /* Rewrite End */  

现在我想在标签之前添加一些数据,所以它看起来像这样:

    Matching  Can be passed on from the environment to the individual. This can be from a person, insects or from the physical environment.  Communicable   Some Txt Some Txt   

我在用

 fs.writeFile("Templatexml.xml", data["message"] , function(err) { if(err) { console.log(err); } else { console.log("The file was saved!"); } }); 

它每次我想要读取文件时都完全重写文件,并在此文件上写入额外的内容我该怎么做?

我有一个针对你的问题的hacky解决方案..格式化你这样的xml文件:

   Matching /* Rewrite */  Can be passed on from the environment to the individual. This can be from person, insects or from the physical environment.  Communicable  //cursor  

和附加新数据的代码:

 var fs = require("fs"); var addData = "Some TxtSome Txt "; var cursor = "//cursor"; addData += cursor; fs.readFile("Templatexml.xml", "utf-8",function(err,data) { if(err) { console.log(err); return; } var newData = data.replace(/\/\/cursor/,addData); fs.writeFile("Templatexml.xml", newData , function(err) { if(err) { console.log(err); return; } console.log("done"); }); });