const fs = require('fs'); /** [OPTIONAL] To add custom methods to String */ String.prototype.contains = String.prototype.includes; String.prototype.lines = function lines() { return this.split(/\r?\n/); }; class Config { constructor(args) { /** Node.js needs to call .next() twice */ args.next(); args.next(); let query = args.next().value; if (!query) { throw new Error(`Didn't get a query string`); } let filename = args.next().value; if (!filename) { throw new Error(`Didn't get a file name`); } this.query = query; this.filename = filename; this.caseSensitive = !('CASE_INSENSITIVE' in process.env); } } function search(query, contents) { return contents.lines() .filter(line => line.contains(query)); } function searchCaseInsensitive(query, contents) { const lowercasedQuery = query.toLowerCase(); return contents.lines() .filter(line => line.toLowerCase().contains(lowercasedQuery)); } function run(config) { try { const contents = fs.readFileSync(config.filename, 'utf8'); const results = config.caseSensitive ? search(config.query, contents) : searchCaseInsensitive(config.query, contents); for (const line of results) { console.log(`${line}`); } } catch (e) { console.error(`Application error: ${e.message}\n`); } } module.exports = { Config, run, }; /** No standard library for testing in Node.js */