» Make grep CLI App in Node.js » 2. Development » 2.2 Initial Version

Initial Version

Run the following command to initialize a Node.js project. This will create a package.json file, which holds metadata about the project and its dependencies.

npm init

Create lib/grep.js:

function grep(pattern, text) {
    const lines = text.split('\n');
    const regex = new RegExp(pattern);
    const matchingLines = lines.filter(line => regex.test(line));
    return matchingLines.map(line => stripLeft(line));
}

function stripLeft(s) {
    // Use the replace method to remove leading spaces and tabs
    return s.replace(/^[ \t]+/, '');
}

module.exports = {
    grep
};

The RegExp object provides support for regular expressions, which are powerful tools for pattern matching and text manipulation.

Create bin/grepjs:

#!/usr/bin/env node

const fs = require('fs');

const { grep } = require('../lib/grep');

function main() {
    // pattern and file name
    const pattern = process.argv[2];
    const fileName = process.argv[3];

    if (!pattern || !fileName) {
        console.error('Usage: grepjs <pattern> <file>');
        process.exit(1);
    }

    // Read the file asynchronously
    fs.readFile(fileName, 'utf8', (err, data) => {
        if (err) {
            console.error(`Error reading file: ${err.message}`);
            process.exit(1);
        }

        // Call grep function and log the result
        const result = grep(pattern, data);
        console.log(result.join('\n'));
    });
}

main();

Ensure that the file has execute permissions. You can do this by running the following command in the terminal:

chmod +x bin/grepjs

process.argv is used for parsing command-line arguments.

Run the CLI script like this:

# search "line" in file lib/grep.js
./bin/grepjs line lib/grep.js

You will get result lines like below:

const lines = text.split('\n');
const matchingLines = lines.filter(line => regex.test(line));
return matchingLines.map(line => stripLeft(line));
PrevNext