简体   繁体   中英

How to load data from offline text word list into string?

Working on an application that checks HTML documents to see if they contain specific words. Using fs.readFileSync to read the HTML, then using fs.writeFile to write it to a text document. Then checks the text document to see if it contains the defined words.

The way word list id defined in the code is:

var words = ./wordlist.txt

If defined the words separately in variables, it works fine, eg

var words = "stack", "cats", "dogs"

but if reading them from the text file which is formatted like

"stack", "cats", "dogs"

it stops working and return a string saying the words were not found.

The way I'm reading the word list file is this:

var posWord = "./wordlist.txt";
var positiveWords = fs.readFileSync(posWord, 'utf8', function(err) {
    if (err) {
        console.log("There was an error in reading the Positive Word list, refer to wordFunc()")
    }
});

console.log(positiveWords) , gives the whole word list with the correct formatting

When you try to read them from the .txt file it will return as a string which represent the line , not as array as you expected So you hav to convert it into array with split() function

var posWord = "./wordlist.txt";
var positiveWords = fs.readFileSync(posWord, 'utf8',   function (err) {
if (err) {console.log("There was an error in reading the Positive Word list, refer to wordFunc()")}})
Words=posWord.split(',');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM