【问题标题】:How do I delete a line at the end of the file and put it at the top of the file?如何删除文件末尾的一行并将其放在文件顶部?
【发布时间】:2021-05-11 21:58:17
【问题描述】:

这是我当前的代码:

const rl = require("readline");
const fs = require("fs");

const ri = rl.createInterface({
  input: fs.createReadStream("dot-error.log"),
  output: process.stdout,
  console: false,
});

ri.on("line", function (line: string) {
  const append: string = line.substring(line.indexOf("\n") + 1);   
});

我将如何创建一个 for 循环来获取 dot-error.log 中文件末尾的行并将其粘贴到文件顶部并删除该行(在文件末尾?谢谢!

【问题讨论】:

    标签: javascript node.js filesystems fs


    【解决方案1】:

    删除最后一行,然后放在最上面

    var fs = require("fs");
    
    var lines = fs.readFileSync("dot-error.log", 'utf8'); // read the file
    lines = lines.trim().split('\n'); // remove empty lines and split using \n
    var lastLine = lines.pop() // get last line
    lines.unshift(lastLine); // prepend last line
    fs.writeFileSync("dot-error.log", lines.join('\n')); // write
    

    编辑:颠倒顺序

    var lines = fs.readFileSync("dot-error.log", 'utf8');
    lines = lines.trim().split('\n');
    lines.reverse();
    fs.writeFileSync("dot-error.log", lines.join('\n'));
    

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 2017-08-09
      • 1970-01-01
      相关资源
      最近更新 更多