Skip to content

Commit 692a1bc

Browse files
committed
fix(wasm): add read_file impl for WasmEnvironment
1 parent 01e0f09 commit 692a1bc

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

crates/rhai-wasm/src/environment.rs

+16
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ pub(crate) struct WasmEnvironment {
171171
js_on_stderr: Function,
172172
js_glob_files: Function,
173173
js_read_file: Function,
174+
js_write_file: Function,
174175
js_sleep: Function,
175176
js_is_absolute: Function,
176177
js_cwd: Function,
@@ -203,6 +204,9 @@ impl From<JsValue> for WasmEnvironment {
203204
js_read_file: js_sys::Reflect::get(&val, &JsValue::from_str("js_read_file"))
204205
.unwrap()
205206
.into(),
207+
js_write_file: js_sys::Reflect::get(&val, &JsValue::from_str("js_write_file"))
208+
.unwrap()
209+
.into(),
206210
js_is_absolute: js_sys::Reflect::get(&val, &JsValue::from_str("js_is_absolute"))
207211
.unwrap()
208212
.into(),
@@ -308,6 +312,18 @@ impl Environment for WasmEnvironment {
308312
Ok(Uint8Array::from(ret).to_vec())
309313
}
310314

315+
async fn write_file(&self, path: &Path, bytes: &[u8]) -> Result<(), anyhow::Error> {
316+
let path_str = JsValue::from_str(&path.to_string_lossy());
317+
let this = JsValue::null();
318+
let data = JsValue::from(js_sys::Uint8Array::from(bytes));
319+
let res: JsValue = self.js_write_file.call2(&this, &path_str, &data).unwrap();
320+
321+
JsFuture::from(Promise::from(res))
322+
.await
323+
.map(|_| ())
324+
.map_err(|err| anyhow!("{:?}", err))
325+
}
326+
311327
fn is_absolute(&self, path: &Path) -> bool {
312328
let path_str = JsValue::from_str(&path.to_string_lossy());
313329
let this = JsValue::null();

editors/vscode/src/server.ts

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ process.on("message", async (d: RpcMessage) => {
3131
glob: p => glob.sync(p),
3232
isAbsolute: p => path.isAbsolute(p),
3333
readFile: path => fsPromise.readFile(path),
34+
writeFile: (path, data) => fsPromise.writeFile(path, data),
3435
stderr: process.stderr,
3536
stdErrAtty: () => process.stderr.isTTY,
3637
stdin: process.stdin,

js/core/src/environment.ts

+5
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ export interface Environment {
3636
* Read a file at the given path.
3737
*/
3838
readFile: (path: string) => Promise<Uint8Array>;
39+
/**
40+
* Write a file at the given path.
41+
*/
42+
writeFile: (path: string, data: Uint8Array) => Promise<void>;
3943
/**
4044
* Search a glob file pattern and return the matched files.
4145
*/
@@ -93,6 +97,7 @@ export function convertEnv(env: Environment): any {
9397
js_url_to_file_path: env.urlToFilePath,
9498
js_sleep: env.sleep,
9599
js_read_file: env.readFile,
100+
js_write_file: env.writeFile,
96101
};
97102
}
98103

0 commit comments

Comments
 (0)