js如何引入wasm文件
js引入wasm文件
js代碼
<script> /** * @param {String} path wasm 文件路徑 * @param {Object} imports 傳遞到 wasm 代碼中的變量 */ function loadWebAssembly (path, imports = {}) { return fetch(path) // 加載文件 .then(response => response.arrayBuffer()) // 轉(zhuǎn)成 ArrayBuffer .then(buffer => WebAssembly.compile(buffer)) .then(module => { imports.env = imports.env || {} // 開(kāi)辟內(nèi)存空間 imports.env.memoryBase = imports.env.memoryBase || 0 if (!imports.env.memory) { imports.env.memory = new WebAssembly.Memory({ initial: 256 }) } // 創(chuàng)建變量映射表 imports.env.tableBase = imports.env.tableBase || 0 if (!imports.env.table) { // 在 MVP 版本中 element 只能是 "anyfunc" imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' }) } // 創(chuàng)建 WebAssembly 實(shí)例 return new WebAssembly.Instance(module, imports) }) } //調(diào)用 loadWebAssembly('test.wasm') .then(instance => { console.log(instance) const add = instance.exports._Z3addii//取出c里面的方法 const square = instance.exports._Z6squarei//取出c里面的方法 console.log('10 + 20 =', add(10, 20)) console.log('3*3 =', square(3)) console.log('(2 + 5)*2 =', square(add(2 + 5))) }) </script>
可以把c/c++文件編譯成wasm文件,使用emscripten編譯
可以在控制臺(tái)打印一下獲取到你想要的方法
利用wasm實(shí)現(xiàn)讀寫(xiě)本地項(xiàng)目的在線編輯器
本篇內(nèi)容是通過(guò)AI-ChatGPT問(wèn)答和查閱相關(guān)文檔得到的答案。
起因是看到在線Vscode和RemixIde都實(shí)現(xiàn)了在線讀取用戶電腦文件夾作為項(xiàng)目根目錄,達(dá)成讀取、創(chuàng)建、修改、刪除該目錄下所有文件、文件夾的功能。
而在瀏覽器中因?yàn)榘踩詥?wèn)題,光憑javascript本身是做不到這么完整的功能,最多只能讀寫(xiě)單個(gè)文件,還不是無(wú)縫銜接和高兼容性。
其中后者是使用Nodejs開(kāi)發(fā)了Remixd的瀏覽器插件來(lái)實(shí)現(xiàn),而前者就是利用近年發(fā)展起來(lái)的wasm/wasi來(lái)實(shí)現(xiàn)的。
由于wasm/wasi更具有光明的前途,本文也是主要結(jié)合AI探索這項(xiàng)功能的基礎(chǔ)實(shí)現(xiàn)方式。
創(chuàng)建一個(gè)新的Rust項(xiàng)目
cargo new --lib wasm-example cd wasm-example
在Cargo.toml文件中添加依賴項(xiàng)
[lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"
創(chuàng)建一個(gè)名為lib.rs的文件
并添加以下代碼:
use std::fs; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn read_folder(folder_path: &str) -> Result<Vec<String>, JsValue> { let entries = fs::read_dir(folder_path) .map_err(|err| JsValue::from_str(&format!("Error reading folder: {}", err)))?; let file_names: Vec<String> = entries .filter_map(|entry| { entry.ok().and_then(|e| e.file_name().into_string().ok()) }) .collect(); Ok(file_names) } #[wasm_bindgen] pub fn write_file(file_path: &str, content: &str) -> Result<(), JsValue> { fs::write(file_path, content) .map_err(|err| JsValue::from_str(&format!("Error writing file: {}", err)))?; Ok(()) }
在項(xiàng)目根目錄下運(yùn)行以下命令
將Rust代碼編譯為Wasm模塊:
wasm-pack build --target web --out-name wasm --out-dir ./static
在前端HTML文件中引入生成的Wasm模塊
并使用JavaScript與Wasm進(jìn)行交互:
<body> <input type="file" id="folderInput" webkitdirectory directory multiple> <ul id="fileList"></ul> <input type="text" id="fileNameInput" placeholder="文件名"> <textarea id="fileContentInput" placeholder="文件內(nèi)容"></textarea> <button id="writeButton">寫(xiě)入文件</button> <script> import init, {read_folder, write_file} from './static/wasm.js'; async function run() { await init(); const folderInput = document.getElementById('folderInput'); const fileListElement = document.getElementById('fileList'); folderInput.addEventListener('change', async (event) => { const files = event.target.files; fileListElement.innerHTML = ''; for (let i = 0; i < files.length; i++) { const file = files[i]; const listItem = document.createElement('li'); listItem.textContent = file.name; fileListElement.appendChild(listItem); const fileContent = await readFile(file); console.log(fileContent); } }); const writeButton = document.getElementById('writeButton'); writeButton.addEventListener('click', async () => { const fileName = document.getElementById('fileNameInput').value; const fileContent = document.getElementById('fileContentInput').value; await writeFile(fileName, fileContent); }); } function readFile(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = (e) => { resolve(e.target.result); }; reader.onerror = (e) => { reject(e.target.error); }; reader.readAsText(file); }); } async function writeFile(fileName, fileContent) { try { await write_file(fileName, fileContent); console.log('File written successfully'); } catch (error) { console.error('Error writing file:', error); } } run(); </script> </body>
你可以使用JavaScript中的File API來(lái)實(shí)現(xiàn)以編程方式觸發(fā)文件夾選擇的行為,而不是通過(guò)點(diǎn)擊元素。
以下是一個(gè)示例代碼,演示如何使用JavaScript創(chuàng)建一個(gè)元素,并通過(guò)點(diǎn)擊標(biāo)簽來(lái)觸發(fā)文件夾選擇:
<body> <a href="#" rel="external nofollow" id="folderLink">選擇文件夾</a> <ul id="fileList"></ul> <script> const folderLink = document.getElementById('folderLink'); const fileListElement = document.getElementById('fileList'); folderLink.addEventListener('click', (event) => { event.preventDefault(); const folderInput = document.createElement('input'); folderInput.type = 'file'; folderInput.webkitdirectory = true; folderInput.directory = true; folderInput.multiple = true; folderInput.addEventListener('change', (event) => { const files = event.target.files; fileListElement.innerHTML = ''; for (let i = 0; i < files.length; i++) { const file = files[i]; const listItem = document.createElement('li'); listItem.textContent = file.name; fileListElement.appendChild(listItem); } }); folderInput.click(); }); </script> </body>
當(dāng)用戶選擇文件夾后,會(huì)觸發(fā)change事件,我們可以在事件處理程序中獲取選擇的文件列表,并將文件名顯示在頁(yè)面上。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
在iframe中使bootstrap的模態(tài)框在父頁(yè)面彈出問(wèn)題
這篇文章主要介紹了在iframe中使bootstrap的模態(tài)框在父頁(yè)面彈出問(wèn)題,解決方法非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-08-08微信小程序 如何獲取網(wǎng)絡(luò)狀態(tài)
這篇文章主要介紹了微信小程序 如何獲取網(wǎng)絡(luò)狀態(tài),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07原生JS實(shí)現(xiàn)京東查看商品點(diǎn)擊放大
這篇文章主要為大家詳細(xì)介紹了原生JS實(shí)現(xiàn)京東查看商品點(diǎn)擊放大,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12js實(shí)現(xiàn)異步循環(huán)實(shí)現(xiàn)代碼
這篇文章主要介紹了js實(shí)現(xiàn)異步循環(huán)實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-02-02JavaScript實(shí)現(xiàn)基于Cookie的存儲(chǔ)類實(shí)例
這篇文章主要介紹了JavaScript實(shí)現(xiàn)基于Cookie的存儲(chǔ)類,實(shí)例分析了javascript通過(guò)cookie實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ)的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04innerText和innerHTML 一些問(wèn)題分析
盡管DOM帶來(lái)了動(dòng)態(tài)修改文檔的能力,但對(duì)開(kāi)發(fā)人員來(lái)說(shuō),這還不夠。IE4.0為所有的元素引入了兩個(gè)特性,以更方便的進(jìn)行文檔操作,這兩個(gè)特性是innerText和innerHTML。2009-05-05JS多個(gè)矩形塊選擇效果代碼(模擬CS結(jié)構(gòu))
非常不錯(cuò)的可以選擇多個(gè)矩形塊的功能代碼2008-11-11基于JavaScript實(shí)現(xiàn)單選框下拉菜單添加文件效果
這篇文章主要介紹了基于JavaScript實(shí)現(xiàn)單選框下拉菜單添加文件效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06Javascript數(shù)組的排序 sort()方法和reverse()方法
JavaScript提供了sort()方法和reverse()方法,使得我們可以簡(jiǎn)單的對(duì)數(shù)組進(jìn)行排序操作和逆序操作2012-06-06