Skip to content

Instantly share code, notes, and snippets.

@ch4nd4n
Created March 31, 2023 10:32
Show Gist options
  • Select an option

  • Save ch4nd4n/612de744ad0b6a0e0537f6f8672ff453 to your computer and use it in GitHub Desktop.

Select an option

Save ch4nd4n/612de744ad0b6a0e0537f6f8672ff453 to your computer and use it in GitHub Desktop.
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();
});
});
});
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