我使用了fs.readFile()
和fs.readFileSync()
来读取“words_alpha.txt”。该文件可在以下网址公开获得:https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt
即使查询test
与words_alpha.txt
文件行数组中的单词相匹配,JSON也总是以{ includes: false, indexFound: false, found: undefined, forFound: false }
作为响应,并使用以下JavaScript代码:
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/test_validation', function(req, res, next) {
const { test } = req.query;
fs.readFile('words_alpha.txt', function(err, data) {
const words = data.toString().split('\n');
const includes = words.includes(test);
const indexFound = words.indexOf(test) > -1;
const found = words.find(word => word === test);
let forFound = false;
for (i in words) {
if (words[i] === test) {
forFound = true;
break;
}
}
res.json({ includes, indexFound, found, forFound });
});
});
为什么words.includes(test)
、words.indexOf(test)
和words.find(word => word === test)
找不到任何匹配,甚至无法与for (i in words) if (words[i] === test)
匹配?但是“words_alpha.txt”words
可以用for (i in words) console.log(words[i])
逐个记录,但需要几秒钟才能完成。
发布于 2019-03-21 02:55:02
问题是,您使用的文件具有Windows样式的行尾(CR、LF或\r\n
,表示为字符),并且您正在按Unix样式的行尾(LF或\n
)拆分,这会产生不正确的单词数组:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("\n");
console.log(words);
console.log(words.includes("apple"))
或者,您可以仅按Windows行尾拆分,但您可能会冒着代码不适用于Unix行尾的风险:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("\r\n");
console.log(words);
console.log(words.includes("apple"))
或者,您也可以将文件转换为Unix文件结尾,您的代码将无需更改即可工作:
const stringOfWords = "apple\nbroccoli\ncarrot"; //unix line endings
console.log(stringOfWords)
const words = stringOfWords.split("\n");
console.log(words);
console.log(words.includes("apple"))
或者,您可以修剪单词以删除空格,从而能够处理任何一行结尾,但对于大文件来说,这可能是一个潜在的繁重操作:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split("\n")
.map(word => word.trim());
console.log(words);
console.log(words.includes("apple"))
或者,对于Windows或Unix行结尾,也可以按正则表达式拆分:
const stringOfWords = "apple\r\nbroccoli\r\ncarrot"; //windows line endings
console.log(stringOfWords)
const words = stringOfWords.split(/\r?\n/);
console.log(words);
console.log(words.includes("apple"))
https://stackoverflow.com/questions/55267877
复制相似问题