我有一个长度为 X 的文件,它正在被长度为 X-Y 的字符串覆盖。问题是,该文件仍然保留 X-Y 过去的信息,因此它与第一个较长的文件一样长。所以这是我的测试输出,它让我适合:
文件开头为:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "FruitSalad",
"bNewBoolean": false,
"iNewNumber": 14.2,
"anNewArray": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
],
"oNewObject": {
"bToBeOrNotToBe": true,
"sFinishQuote": "That is the question"
}
}
将写入的数据更改为以下内容:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "YummyYummy",
"bNewBoolean": true,
"iNewNumber": 2.14,
"anNewArray": [
10,
9
],
"oNewObject": {
"bToBeOrNotToBe": false,
"sNewQuote": "To die, to sleep, no more"
}
}
之后,文件现在是:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "YummyYummy",
"bNewBoolean": true,
"iNewNumber": 2.14,
"anNewArray": [
10,
9
],
"oNewObject": {
"bToBeOrNotToBe": false,
"sNewQuote": "To die, to sleep, no more"
}
} "bToBeOrNotToBe": true,
"sFinishQuote": "That is the question"
}
}}
看到物体末端的垃圾了吗?它是上一个文件留下的,即使我用以下代码写出来:
DeviceConfiguration.prototype.SetPersistentUserOption = function(sNewOptionName, NewOption)
{
var sNewFile = "";
var fs = require('fs');
//if one of the primitive types, it's simple, just add it to object
if(typeof(NewOption) == "string" || typeof(NewOption) == "number" || typeof(NewOption) == "boolean")
{
this.oPersistentUserOptions[sNewOptionName] = NewOption;
}
else if(NewOption instanceof Array)
{
//blank out array if it was there already
this.oPersistentUserOptions[sNewOptionName] = [];
//now go back and copy each element over one at a time
for(var nIndex = 0; nIndex < NewOption.length; nIndex++)
{ this.oPersistentUserOptions[sNewOptionName][nIndex] = NewOption[nIndex]; }
}
else if(NewOption instanceof Object)
{
//blank out object if it was there already
this.oPersistentUserOptions[sNewOptionName] = {};
//now go back and copy each element over one at a time
for(Member in NewOption)
{ this.oPersistentUserOptions[sNewOptionName][Member] = NewOption[Member];
}
}
//stringify the object, and make it pretty with options null, 4
sNewFile = JSON.stringify(this.oPersistentUserOptions, null, 4);
//write to the file, parameter is immediately in object memory though
fs.writeFile(PERSISTENT_USER_SELECTED_OPTIONS_FILENAME, sNewFile, function(err){console.log(err);});
//fs.writeFileSync(PERSISTENT_USER_SELECTED_OPTIONS_FILENAME, sNewFile);
console.log(sNewFile.length);
console.log(sNewFile);
};
我已检查以确保 sNewFile 变量的长度正确,确实如此。我还在后续写入磁盘之间暂停了长达 6 秒的时间,所以我看不出这怎么可能是一个计时问题。
如果我使用 writeFileSync 问题就会消失,但我确实没有选择为此应用程序执行同步写入,因为我对时间要求很严格,并且不想放慢写入磁盘的速度。
我使用的是 node.js 0.8.21,但看起来该接口与最新版本之间的 fs 接口没有发生任何变化。
还有人打过类似的东西吗?这让我很不舒服。 。 。