Open In App

How to Work with ‘word-count’ Module in Node.js ?

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The ‘work-count‘ module is a simple and lightweight external NPM module that can count the number of words in a string. This module provides a count() function, which counts the number of words by ignoring any special characters or symbols in the string. 

Installation: First, we have to install the module using the command given below. Open the terminal, navigate to the same folder as your project, and then give the same command to install the module. After installation, a package.json file gets added to your project folder, which contains all the information regarding the installed modules.

$ npm install word-count  

 Installation

Use the module: To use this module in the application, we have to incorporate the module into the project using the require keyword. Give the string to the module to process it and then show the output in the console of the terminal.

const wordCount = require("word-count");

 

Run: After writing all the code, open the terminal and use the given command to run the JavaScript file. This will count the words in the entered string and show the result in the console. Give different strings again to again, which will produce different output every time. 

$ node index.js

where index.js is the javascript file name.

Example 1:

Javascript




const wordCount = require("word-count");
  
// String to count
const str = 
"GeeksforGeeks is the best website for computer science";
  
const count = wordCount(str);
  
console.log(`Number of words: ${count}`);


Output:

output 1

Example 2:

Javascript




const wordCount = require('word-count');
  
const myString = 
'Hello world! This string contains five words.';
  
const numWords = wordCount(myString);
  
console.log(numWords); // 5


Output:

output 2 

Note: Enter the different strings of different lengths, to get different results.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads