如何使用Node JS向现有文件添加一些额外数据 [英] How to add some extra data to an existing file using node js
本文介绍了如何使用Node JS向现有文件添加一些额外数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的文件
<?xml version="1.0" encoding="utf-8"?>
<Quiz>
<title>Matching</title>
/* Rewrite */
<questions>
<question>Can be passed on from the environment to the individual. This can be from a person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>
/* Rewrite End */
</quiz>
现在,我想在</quiz>
标记之前添加一些数据,使其看起来像这样:
Now i want to add some data before </quiz>
tag so it will look like this:
<?xml version="1.0" encoding="utf-8"?>
<Quiz>
<title>Matching</title>
<questions>
<question>Can be passed on from the environment to the individual. This can be from a person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>
<questions>
<question>Some Txt</question>
<answer>Some Txt</answer>
</questions>
</quiz>
我正在使用
fs.writeFile("Templatexml.xml", data["message"] , function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
每次我要读取文件并在此文件上写入多余内容时,它将完全重写文件.我该怎么做?
It fully rewrites the file every time I want to read the file and and write the extra content on this file how can i do this?
推荐答案
对于您的问题,我有一种可靠的解决方案. 像这样格式化xml文件:
I have a kind of hacky solution for your problem.. format you xml file like this:
<?xml version="1.0" encoding="utf-8"?>
<Quiz>
<title>Matching</title>
/* Rewrite */
<questions>
<question>Can be passed on from the environment to the individual. This can be from person, insects or from the physical environment. </question>
<answer>Communicable</answer>
</questions>
//cursor
</quiz>
以及附加新数据的代码:
and the code for appending new data:
var fs = require("fs");
var addData = "<questions><question>Some Txt</question><answer>Some Txt</answer> </questions>";
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");
});
});
这篇关于如何使用Node JS向现有文件添加一些额外数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文