我正在使用 nim 的webgui包開發桌面應用程式,它的作業方式類似于電子,因為它使用 HTML CSS JS 呈現 gui。但是,它不是捆綁自己的瀏覽器并在 node 中使用后端,而是使用作業系統提供的瀏覽器(Linux/GNOME 下的 Epiphany、Windows 下的 Edge、iOS 下的 Safari)并允許在 nim 中撰寫后端。
在這種情況下,我基本上是在 Angular 中撰寫一個 SPA,并且需要在編譯時將 HTML、JS 和 CSS 檔案加載到我的二進制檔案中。從已知的絕對檔案路徑讀取不是問題,您可以使用 nim 的staticRead方法。但是,我想避免一直在我的應用程式代碼中調整檔案名,例如,當 SPA 的新版本將檔案名main.a72efbfe86fbcbc6.js從main.b72efbfe86fbcbc6.js.
有一個迭代器std/os可以在運行時使用,稱為walkFilesand walkPattern,但在 compileTime 使用時會失敗!
import std/[os, sequtils, strformat, strutils]
const resourceFolder = "/home/philipp/dev/imagestable/html" # Put into config file
const applicationFiles = toSeq(walkFiles(fmt"{resourceFolder}/*"))
/home/philipp/.choosenim/toolchains/nim-#devel/lib/pure/os.nim(2121, 11) Error: cannot 'importc' variable at compile time; glob
我該如何解決這個問題?
uj5u.com熱心網友回復:
感謝來自 nim 的不和諧服務器的 enthus1ast,我得到了一個答案:使用帶有迭代器的collect 宏。walkDir
walkDir迭代器不使用僅在運行時可用的東西,因此可以在編譯時安全地使用。使用 collect 宏,您可以遍歷特定目錄中的所有檔案并將它們的路徑收集到編譯時序列中!
基本上,您開始撰寫 collect-block,這是一個簡單的 for 回圈,在其末尾計算某種形式的值。collect 宏會將它們全部放入最后的 seq 中。
最終結果看起來很像這樣:
import std/[sequtils, sugar, strutils, strformat, os]
import webgui
const resourceFolder = "/home/philipp/dev/imagestable/html"
proc getFilesWithEnding(folder: string, fileEnding: string): seq[string] {.compileTime.} =
result = collect:
for path in walkDir(folder):
if path.path.endswith(fmt".{fileEnding}"): path.path
proc readFilesWithEnding(folder: string, fileEnding: string): seq[string] {.compileTime.} =
result = getFilesWithEnding(folder, fileEnding).mapIt(staticRead(it))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505070.html
