Node.js: Count the number of lines in a file

前端 未结 10 646
一向
一向 2020-12-02 23:02

I have large text files, which range between 30MB and 10GB. How can I count the number of lines in a file using Node.js?

I hav

10条回答
  •  自闭症患者
    2020-12-02 23:48

    If you use Node 8 and above, you can use this async/await pattern

    const util = require('util');
    const exec = util.promisify(require('child_process').exec);
    
    async function fileLineCount({ fileLocation }) {
      const { stdout } = await exec(`cat ${fileLocation} | wc -l`);
      return parseInt(stdout);
    };
    
    // Usage
    
    async someFunction() {
      const lineCount = await fileLineCount({ fileLocation: 'some/file.json' });
    }
    

提交回复
热议问题