I am creating a this program which finds the common words of 2 word files and then creates a new file with just the common words. I'm using the readline module to read each word of first word file and then store that word in a Trie. After that has been completed, I'm trying to read the words from the other word file and if it is in trie, I'm writing to file.
I'm using promises to make sure that the events happen in sequence but the second time the 'line' event is not triggered.
'use strict'
const readLine = require('readline');
const fs = require('fs');
const wordList = require('./Trie.js');
function createTrie(reader, trie) {
return new Promise((resolve, reject) => {
if(typeof reader === 'undefined' || reader === null)
reject('Failed')
reader.on('line', line => trie.add(line))
reader.on('close', () => {
console.log('done')
resolve(trie)
})
})
}
function findCommon(reader, trie) {
return new Promise((resolve, reject) => {
if(typeof reader === 'undefined' || reader === null) {
console.log('failed')
reject('Failed')
}
let commonWords = ''
console.log('we are here')
reader.on('line', (line) => {
console.log(line) // This does not output
if(line.length > 2 && trie.search(line)) {
let word = line + '\n'
commonWords += word
}
})
reader.on('close', () => {
fs.writeFile('wordlist.txt', commonWords, (err) => {
if(err) {
console.log(err)
reject('error')
}
console.log('written')
resolve('Success')
})
})
})
}
let reader_1 = readLine.createInterface({
input: fs.createReadStream('words/enable2k.txt')
})
let reader_2 = readLine.createInterface({
input: fs.createReadStream('words/engmix.txt')
})
createTrie(reader_1, wordList)
.then((trie) => findCommon(reader_2, trie))
.then((data) => console.log(data))
The above code gives the below output
done
we are here
The 'line' event is not triggered. It seems like I'm not using readline correctly but I'm not sure.
Any help is appreciated!
via Utkarsh
No comments:
Post a Comment