如果您將所有頁面存儲在「views」目錄中,則可以使用fs讀取每個文件並搜索其內容。
我已經做的東西一個簡單的例子,你可以做這樣做:
// The directory containing all your pages
let directoryToYourPagesOrHTMLFiles = "/your/directory/";
// Require fs so you can get all the files and file content
const fs = require("fs");
// Require html-to-text so you can parse the HTML in the files
// into text so you can search on the data easier
let htmlToText = require('html-to-text'); // npm install --save html-to-text
// Run this function when a user enters a character
function userTyped(inputValue) {
// Foreach file in the directory
fs.readdir(directoryToYourPagesOrHTMLFiles).forEach(filename => {
// Read the file contents
fs.readFile(directoryToYourPagesOrHTMLFiles + "/" + filename, "utf8", (err, data) => {
// If there was an error reading the file log it
if(err) {
console.log(err);
} else {
// If there was no error, parse the HTML into text
let text = htmlToText.fromString(data);
// Perform your search on the next using the inputValue
// Example Search:
if(text.indexOf(inputValue) > -1) {
// Display the page in your search results
displaySearchResult(directoryToYourPagesOrHTMLFiles + "/" + filename);
}
}
});
});
}
function displaySearchResult(pagePath) {
/*
Add the page to a results page
*/
}
我沒有測試這一點,因爲它在匆忙做到了,但它表明你需要什麼概念做!
希望這可以幫助你!
您是要搜索HTML源代碼,還是隻搜索文本內容? – Zac
@Zac頁面的內容。所以基本上標題,段落,任何可以容納文本的元素。與網頁上的搜索欄或當前頁面的查找功能類似,可以這樣做。我想在基本解析出文本後搜索文本,省略代碼部分或html標記 – user7258936
根據您擁有多少頁面以及webcontents.findInPage()函數的速度有多快,可能會加載所有進入一些虛擬環境並在那裏查詢它們。 – Zac