const fs = require('fs') // The word to search for. // We only consider " " to be a word separator. const WORD = 'king' // The number of times the word occurs let count = 0 // A word may be split across chunks, // so store the partial word at the end of the previous chunk let partialWord = '' fs.createReadStream('hamlet.txt', 'utf8') .on('data', chunk => { // Split each chunk into words const words = chunk.split(' ') // Add the partial word at the end of the previous chunk words[0] = partialWord + words[0] // Store the partial word at the end of this chunk partialWord = words.pop() // Count the number of words that match our search word for (const word of words) { if (word.toLowerCase() === WORD) count++ } }) .on('end', () => { // Process the word at the end of the last chunk if (partialWord.toLowerCase() === WORD) count++ // "The word king occurs 36 times" console.log(`The word ${WORD} occurs ${count} times`) })