Created
March 31, 2023 10:32
-
-
Save ch4nd4n/612de744ad0b6a0e0537f6f8672ff453 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const countLines = require('./count-lines'); | |
| describe('countLines', () => { | |
| test('counts the number of lines in a file', (done) => { | |
| const filename = 'test-file.txt'; | |
| const expectedLineCount = 3; | |
| countLines(filename, (err, lineCount) => { | |
| expect(err).toBeNull(); | |
| expect(lineCount).toBe(expectedLineCount); | |
| done(); | |
| }); | |
| }); | |
| test('handles errors when reading a file', (done) => { | |
| const filename = 'non-existent-file.txt'; | |
| countLines(filename, (err, lineCount) => { | |
| expect(err).not.toBeNull(); | |
| expect(lineCount).toBeUndefined(); | |
| done(); | |
| }); | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fs = require('fs'); | |
| const readline = require('readline'); | |
| function countLines(filename, callback) { | |
| let lineCount = 0; | |
| const rl = readline.createInterface({ | |
| input: fs.createReadStream(filename), | |
| crlfDelay: Infinity | |
| }); | |
| rl.on('line', (line) => { | |
| lineCount++; | |
| }); | |
| rl.on('close', () => { | |
| callback(null, lineCount); | |
| }); | |
| rl.on('error', (err) => { | |
| callback(err); | |
| }); | |
| } | |
| module.exports = countLines; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment