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 || {}
// 開辟內(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 實例
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編譯
可以在控制臺打印一下獲取到你想要的方法

利用wasm實現(xiàn)讀寫本地項目的在線編輯器
本篇內(nèi)容是通過AI-ChatGPT問答和查閱相關(guān)文檔得到的答案。
起因是看到在線Vscode和RemixIde都實現(xiàn)了在線讀取用戶電腦文件夾作為項目根目錄,達成讀取、創(chuàng)建、修改、刪除該目錄下所有文件、文件夾的功能。
而在瀏覽器中因為安全性問題,光憑javascript本身是做不到這么完整的功能,最多只能讀寫單個文件,還不是無縫銜接和高兼容性。
其中后者是使用Nodejs開發(fā)了Remixd的瀏覽器插件來實現(xiàn),而前者就是利用近年發(fā)展起來的wasm/wasi來實現(xiàn)的。
由于wasm/wasi更具有光明的前途,本文也是主要結(jié)合AI探索這項功能的基礎(chǔ)實現(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="文件內(nèi)容"></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)建一個元素,并通過點擊標(biāo)簽來觸發(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)用戶選擇文件夾后,會觸發(fā)change事件,我們可以在事件處理程序中獲取選擇的文件列表,并將文件名顯示在頁面上。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
javascript DOM編程實例(智播客學(xué)習(xí))
最近一直在努力學(xué)習(xí)DOM編程這塊,這是目前成就感最強烈的一塊了,畢老師很認(rèn)真的給我們講解了相關(guān)知識,并在網(wǎng)上找了很多做的非常棒的網(wǎng)頁作為例程給我們進行講解2009-11-11
瀏覽器視頻幀操作方法?requestVideoFrameCallback()
這篇文章主要介紹了瀏覽器視頻幀操作方法?requestVideoFrameCallback(),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
JavaScript頁面實時顯示當(dāng)前時間實例代碼
最近因為項目需要,有個需求是讓實時顯示當(dāng)前時間,然后想想這不簡單嗎,自己就動手敲代碼,但是發(fā)現(xiàn)一個問題,通過getMonth()得到月份,總是會比當(dāng)前月份少1,深深覺得實踐出真知啊…之前覺得Date對象挺簡單的,有很多細(xì)節(jié)都沒有注意。下面這篇文章就給大家詳細(xì)介紹下。2016-10-10
javascript中window.open在原來的窗口中打開新的窗口(不同名)
本文給大家介紹使用window.open在原來的窗口中打開新的窗口,涉及到win.open新窗口相關(guān)知識,對本文感興趣的朋友參考下2015-11-11

