|
| 1 | +#!/usr/bin/env node |
| 2 | +import { program } from "commander"; |
| 3 | +import { promises as fs } from "node:fs"; |
| 4 | +import process from "node:process"; |
| 5 | + |
| 6 | +program |
| 7 | + .name("customCat") |
| 8 | + .description("CLI command to concatenate and print files") |
| 9 | + .option("-n, --number", "Number all output lines starting, at 1") |
| 10 | + .option("-b, --nonBlank", "Number only non-blank lines, starting at 1") |
| 11 | + .argument("<files...>", "Files to read"); |
| 12 | + |
| 13 | +program.parse(); |
| 14 | + |
| 15 | +const argv = program.args; |
| 16 | +const options = program.opts(); |
| 17 | + |
| 18 | +let lineNumber = 1; |
| 19 | + |
| 20 | +for (const filePath of argv) { |
| 21 | + try { |
| 22 | + const content = await fs.readFile(filePath, "utf-8"); |
| 23 | + const lines = content.split("\n"); |
| 24 | + |
| 25 | + if (lines[lines.length - 1] === "") lines.pop(); |
| 26 | + |
| 27 | + lines.forEach((line, index) => { |
| 28 | + if (options.nonBlank) { |
| 29 | + if (line.trim() !== "") { |
| 30 | + process.stdout.write(`${(index + 1).toString().padStart(6)} ${line}\n`); |
| 31 | + lineNumber++; |
| 32 | + } else process.stdout.write(`${line}\n`); |
| 33 | + } else if (options.number) { |
| 34 | + process.stdout.write(`${(index + 1).toString().padStart(6)} ${line}\n`); |
| 35 | + } else { |
| 36 | + process.stdout.write(`${line}\n`); |
| 37 | + } |
| 38 | + }); |
| 39 | + } catch (error) { |
| 40 | + console.error(`customCat: ${filePath}: No such file or directory.`); |
| 41 | + } |
| 42 | +} |
0 commit comments