【问题标题】:To merge file in node js? [closed]在节点 js 中合并文件? [关闭]
【发布时间】:2021-07-29 16:49:19
【问题描述】:

我需要删除除最后 500 行之外的所有行。 我将使用 fs 模块。 如果你知道怎么做,请告诉我怎么做!

p.s 我的英语说得不好。我希望你能理解我的文章。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    我只能告诉如何用最后 N 行创建一个副本。

    1. 如果您的系统有tail,并且您不介意使用child_process 模块:
    import child_process from 'child_process';
    
    child_process.exec('tail -n 500 test.txt > test2.txt');
    

    或:

    import child_process from 'child_process';
    import fs from 'fs';
    
    child_process.spawn(
      'tail', ['-n', '500', 'test.txt']
    ).stdout.pipe(fs.createWriteStream('test2.txt'));
    
    1. 如果您的文件不是很大,您可以将其作为一个整体读入内存并使用一些中间结构:
    import fs from 'fs';
    const text = fs.readFileSync('test.txt', 'utf8');
    const lines = text.split('\n');
    fs.writeFileSync('test2.txt', lines.slice(-500).join('\n'));
    
    1. 如果您的文件很大,您可以使用readline 模块逐行读取两次:第一次计算行数,第二次写入最后 N 个。
    import fs from 'fs';
    import readline from 'readline';
    
    (async function main() {
      const counterStream = fs.createReadStream('test.txt');
    
      const counter = readline.createInterface({
        input: counterStream,
        crlfDelay: Infinity,
      });
    
      let lineCount = 0;
      for await (const line of counter) {
        lineCount++;
      }
    
      const startAfter = Math.max(0, lineCount - 500);
    
      const readerStream = fs.createReadStream('test.txt');
      const result = fs.openSync('test2.txt', 'a');
    
      const reader = readline.createInterface({
        input: readerStream,
        crlfDelay: Infinity,
      });
    
      lineCount = 0;
      for await (const line of reader) {
        if (++lineCount > startAfter) fs.writeSync(result, `${line}\n`);
      }
    })();
    

    另请参阅这些问题的答案:

    Remove last n lines from file using nodejs

    NodeJS - How to remove the first line of a text file without read all lines?

    UPD:(可能是幼稚的)尝试模仿 tail -n:

    import fs from 'fs';
    
    const path = 'test.txt';
    const lastLinesLimit = 5;
    
    const fileSize = fs.statSync(path).size;
    const fd = fs.openSync(path);
    
    // Increase the next number appropriately to decrease read calls.
    let bufferSize = Math.min(10, fileSize);
    let buffer = Buffer.alloc(bufferSize);
    
    let stringTail = '';
    let position = fileSize;
    
    while (position !== 0) {
      position -= bufferSize;
      if (position < 0) {
        bufferSize += position;
        buffer = buffer.subarray(0, position);
        position = 0;
      }
      fs.readSync(fd, buffer, 0, bufferSize, position);
      stringTail = buffer.toString() + stringTail;
      if (stringTail.match(/\n(?!$)/g)?.length >= lastLinesLimit) break;
    }
    
    console.log(
      stringTail
        .split(/\n(?!$)/)
        .slice(-lastLinesLimit)
        .join('\n')
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 2012-12-07
      • 2017-02-27
      • 2023-03-25
      • 2018-03-12
      • 2011-07-27
      • 2017-11-04
      相关资源
      最近更新 更多