2017-07-02 149 views
0

我目前正在設計一個電子程序。該計劃的關鍵部分之一是搜索選項。與其他網站類似,您可以在整個網站上搜索與您的查詢相匹配的網頁,我希望在我的程序的「網頁」/「html文件」中搜索並顯示搜索結果。最好是一次一個字母實時顯示,這樣人們可以在輸入時看到結果,但即使是搜索選項也可以。我只需要在我的程序頁面內搜索,而不是外部網站。我無法弄清楚如何開始實現這個,因爲在Electron中不支持PHP。我知道反應可以在一次實時搜索中完成這封信,但我不確定如何搜索其他頁面或如何解析搜索。任何建議,指導方針或框架可幫助我走上正軌。謝謝!在Electron中搜索頁面?

編輯:我也知道webcontents.findInPage()函數,但只搜索當前頁面,而不是項目路徑中的其他頁面。如果我能找到實際搜索的方法,我很好地定義要手動搜索哪些頁面。

+0

您是要搜索HTML源代碼,還是隻搜索文本內容? – Zac

+0

@Zac頁面的內容。所以基本上標題,段落,任何可以容納文本的元素。與網頁上的搜索欄或當前頁面的查找功能類似,可以這樣做。我想在基本解析出文本後搜索文本,省略代碼部分或html標記 – user7258936

+1

根據您擁有多少頁面以及webcontents.findInPage()函數的速度有多快,可能會加載所有進入一些虛擬環境並在那裏查詢它們。 – Zac

回答

0

如果您將所有頁面存儲在「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 
    */ 
} 

我沒有測試這一點,因爲它在匆忙做到了,但它表明你需要什麼概念做!

希望這可以幫助你!

+0

感謝您的回覆。那麼JavaScript/NodeJS?本地有一個HTML到文本的解析器,或者這是我需要設置的第二個包?謝謝,我會看看這是否符合需求,並根據我的情況適應需要的東西! – user7258936

+0

html-to-text是一個不是NodeJS原生的npm包,所以你需要安裝它,我把命令放在require(第9行)旁邊的註釋中。 – y0hami