NodeJS Slip 14A solution

//Slip_14A.js

const fs = require('fs');

// Function to search for a word in a file
function searchWordInFile(filePath, wordToSearch) {

// Read the file
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}

// Split the file content by lines
const lines = data.split('\n');

// Search for the word in each line
lines.forEach((line, lineNumber) => {
if (line.includes(wordToSearch)) {
console.log('Found "${wordToSearch}" in line ${lineNumber + 1}: ${line}');
}
});
});
}

// Usage example
const filePath = 'example.txt'; // Path to your file
const wordToSearch = 'example'; // Word to search for
searchWordInFile(filePath, wordToSearch);

No comments:

Post a Comment