【问题标题】:Deleteing characters from end of a file in Nodejs从Nodejs中的文件末尾删除字符
【发布时间】:2016-08-19 07:55:53
【问题描述】:

我正在使用 fs 模块的 appendFile() 函数将 JSON 数据附加到文件中。

添加后,我需要从文件中删除最后一个字符并添加一个新字符。我尝试使用\b 转义序列删除最后一个字符,但没有成功。

此外,了解如何编辑文件中间的字符会很有帮助。

【问题讨论】:

  • 您不能“编辑”文件中间的字符。您可以使用fs.write()position 参数将任意数量的字节写入该文件的该位置(如果文件以适当的模式打开)。您还可以使用fs.truncate(...) 缩短文件的长度。
  • 虽然如果您要将数据附加到文件中,为什么不在将数据附加到文件之前修复数据,然后您不必在事后修复文件?

标签: node.js file file-writing


【解决方案1】:

你可以试试这个; 使用

将文件内 JSON 的右大括号“]”替换为“逗号”
var fd = fs.openSync("file.txt", "r+");
var currentDataLength = data.length;
var buf = new Buffer(","); // create a buffer
  if(currentDataLength > 2) {
    fs.writeSync(fd, buf, 0, buf.length, currentDataLength-1); // this replaces '[' with ',' to separate the objects in the JSON
}

var inputData = `${JSON.stringify({testData: 'Dare Something'})}]`; //  notice that array closing brace ']' is included
currentDataLength += inputData.length; //update the variable holding the JSON Data length of you file

fs.writeFileSync('file.txt', inputData, {encoding: 'utf8', flag: 'a+'}); //updates file

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 2011-03-07
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2013-04-28
    • 2014-08-14
    相关资源
    最近更新 更多