1
我瀏覽過其他問題在這裏與我的問題有關,但他們不在我的情況下工作,或者我錯誤地使用它,需要更好的解釋。搜索文件的關鍵字,然後登錄該行的其餘部分
我正在閱讀一個大文件,看第一個單詞,看它是否匹配來自用戶的輸入,然後如果是這樣,我想console.log
該行的其餘部分。
FILE.TXT
#one: This is the first line
#two: This is the second line
#three: This is the third line
etc
節點的js
// Take in user input
var msgSplit = userInput.split(" ");
if (msgSplit[0].startsWith("#") {
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('Custom_Phrases')
});
lineReader.on('line', function(line) {
if(line.indexOf(msgSplit[0]) < 0) {
console.log(line);
}
});
}
這工作,種,但它返回一個我想之後的行。如果可能的話,例如,如果用戶輸入#one,這是第一行記錄到控制檯。
'line.indexOf(msgSplit [0])<0'意味着您的用戶輸入不被發現。因此只顯示行,與用戶輸入不匹配。我會爲if語句嘗試'line.indexOf(msgSplit [0])> = 0'。 –
男孩之後,我覺得有點愚蠢,謝謝你的作品。我對用戶的例子感到困惑,因爲其他人是錯誤日誌,所以我認爲他的第一條語句會打印出該行。 –
如果您沒有自己編寫代碼,很容易看到這樣的錯誤。去年我犯了數百個這樣的錯誤,不得不問朋友「嘿,我的代碼出了什麼問題?」。而且他們臉上露出微笑,我知道...... ;-) –