javascript - 使用 node.js 覆盖文件中的一行

标签 javascript node.js filesystems

使用 node.js 覆盖大型 (2MB+) 文本文件中一行的最佳方法是什么?

我目前的方法涉及

  • 将整个文件复制到缓冲区中。
  • 通过换行符 (\n) 将缓冲区拆分为数组。
  • 使用缓冲区索引覆盖该行。
  • 然后用 \n 连接后用缓冲区覆盖文件。

最佳答案

首先,您需要搜索该行的起点和终点。接下来,您需要使用一个函数来替换该行。我有使用我的一个库的第一部分的解决方案:Node-BufferedReader .

var lineToReplace = "your_line_to_replace";
var startLineOffset = 0;
var endLineOffset = 0;

new BufferedReader ("your_file", { encoding: "utf8" })
    .on ("error", function (error){
        console.log (error);
    })
    .on ("line", function (line, byteOffset){
        startLineOffset = endLineOffset;
        endLineOffset = byteOffset - 1; //byteOffset is the offset of the NEXT byte. -1 if it's the end of the file, if that's the case, endLineOffset = <the file size>

        if (line === lineToReplace ){
            console.log ("start: " + startLineOffset + ", end: " + endLineOffset +
                    ", length: " + (endLineOffset - startLineOffset));
            this.interrupt (); //interrupts the reading and finishes
        }
    })
    .read ();

关于javascript - 使用 node.js 覆盖文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692835/

相关文章:

javascript - 在生成的 HTML Ruby on Rails 中,参数列表 onclick 之后缺少 )

javascript - 我如何使用 jquery 从输入 'type=text' 元素中获取文本?

node.js - Mongodb使用过滤器在子文档中获取记录

node.js - 检查文件是否存在于我的服务器上 - Node js

javascript - 防止AJAX表单提交两次?

javascript - jQuery 导航 - 需要定位和 Accordion 行为方面的帮助

javascript - 为什么刷新页面后我的 WebSocket 连接会关闭?

javascript - 如何在同一条消息中发送附件和嵌入内容?

php - 如何在 php 事务中执行文件系统操作?

node.js - 在 Ubuntu 上使用 fs.writeFileSync 得到错误 : EACCES: permission denied