File Counter

Count lines, words, and characters in a text file.

Start building, submit solution and get feedback from the community.
2Submit Solution
5 upvotes10 upvotes

File Counter

You are required to build a CLI tool using Node.js that counts lines, words, and characters in a text file.

The tool should accept a file path from the terminal. If the user does not pass a file path, it should print a friendly error.

Create a file called notes.txt with this content:

txt
Node makes CLI tools useful.Files are common input.

Here are some example commands you can run to test your CLI:

bash
node file-counter.js notes.txtnode file-counter.js missing.txtnode file-counter.js

On successful execution, the output should look like this:

txt
File: notes.txtLines: 2Words: 9Characters: 52

If the file cannot be read, print a friendly error:

txt
error: could not read file: missing.txt

If the user does not pass a file path, print this error:

txt
error: please provide a file path

Errors should go to stderr, and the command should set a non-zero exit code.

The goal of this project is to practice reading command arguments, loading a file with Node.js, and turning file content into useful counts.

You will need these Node.js APIs:

  • process.argv to read the file path from the terminal.

  • node:fs/promises to read the file contents.

  • node:path to print a clean file name.

Solution

Solution:

js
import { readFile } from 'node:fs/promises';import path from 'node:path';const filePath = process.argv[2];function printError(message) {  console.error(`error: ${message}`);  process.exitCode = 1;}function getFileStats(text) {  return {    lines: text.length === 0 ? 0 : text.split(/\r?\n/).length,    words: text.trim().split(/\s+/).filter(Boolean).length,    characters: text.length,  };}async function main() {  if (!filePath) {    printError('please provide a file path');    return;  }  let text;  try {    text = await readFile(filePath, 'utf8');  } catch {    printError(`could not read file: ${filePath}`);    return;  }  const stats = getFileStats(text);  console.log(`File: ${path.basename(filePath)}`);  console.log(`Lines: ${stats.lines}`);  console.log(`Words: ${stats.words}`);  console.log(`Characters: ${stats.characters}`);}await main();

Join the Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank  out of 28M!

359K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+2.8M

Registered Users

Register yourself
Commit to your growth

+2kevery month

49K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.