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()) // 轉成 ArrayBuffer .then(buffer => WebAssembly.compile(buffer)) .then(module => { imports.env = imports.env || {} // 開辟內存空間 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 實例 return new WebAssembly.Instance(module, imports) }) } //調用 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編譯
可以在控制臺打印一下獲取到你想要的方法
利用wasm實現(xiàn)讀寫本地項目的在線編輯器
本篇內容是通過AI-ChatGPT問答和查閱相關文檔得到的答案。
起因是看到在線Vscode和RemixIde都實現(xiàn)了在線讀取用戶電腦文件夾作為項目根目錄,達成讀取、創(chuàng)建、修改、刪除該目錄下所有文件、文件夾的功能。
而在瀏覽器中因為安全性問題,光憑javascript本身是做不到這么完整的功能,最多只能讀寫單個文件,還不是無縫銜接和高兼容性。
其中后者是使用Nodejs開發(fā)了Remixd的瀏覽器插件來實現(xiàn),而前者就是利用近年發(fā)展起來的wasm/wasi來實現(xiàn)的。
由于wasm/wasi更具有光明的前途,本文也是主要結合AI探索這項功能的基礎實現(xiàn)方式。
創(chuàng)建一個新的Rust項目
cargo new --lib wasm-example cd wasm-example
在Cargo.toml文件中添加依賴項
[lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"
創(chuàng)建一個名為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(()) }
在項目根目錄下運行以下命令
將Rust代碼編譯為Wasm模塊:
wasm-pack build --target web --out-name wasm --out-dir ./static
在前端HTML文件中引入生成的Wasm模塊
并使用JavaScript與Wasm進行交互:
<body> <input type="file" id="folderInput" webkitdirectory directory multiple> <ul id="fileList"></ul> <input type="text" id="fileNameInput" placeholder="文件名"> <textarea id="fileContentInput" placeholder="文件內容"></textarea> <button id="writeButton">寫入文件</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來實現(xiàn)以編程方式觸發(fā)文件夾選擇的行為,而不是通過點擊元素。
以下是一個示例代碼,演示如何使用JavaScript創(chuàng)建一個元素,并通過點擊標簽來觸發(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>
當用戶選擇文件夾后,會觸發(fā)change事件,我們可以在事件處理程序中獲取選擇的文件列表,并將文件名顯示在頁面上。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
在iframe中使bootstrap的模態(tài)框在父頁面彈出問題
這篇文章主要介紹了在iframe中使bootstrap的模態(tài)框在父頁面彈出問題,解決方法非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-08-08js實現(xiàn)異步循環(huán)實現(xiàn)代碼
這篇文章主要介紹了js實現(xiàn)異步循環(huán)實現(xiàn)代碼,需要的朋友可以參考下2016-02-02JavaScript實現(xiàn)基于Cookie的存儲類實例
這篇文章主要介紹了JavaScript實現(xiàn)基于Cookie的存儲類,實例分析了javascript通過cookie實現(xiàn)數(shù)據(jù)存儲的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04基于JavaScript實現(xiàn)單選框下拉菜單添加文件效果
這篇文章主要介紹了基于JavaScript實現(xiàn)單選框下拉菜單添加文件效果的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-06-06Javascript數(shù)組的排序 sort()方法和reverse()方法
JavaScript提供了sort()方法和reverse()方法,使得我們可以簡單的對數(shù)組進行排序操作和逆序操作2012-06-06