diff --git a/oden-js/src/lib.rs b/oden-js/src/lib.rs index 6d6397c5..e4171675 100644 --- a/oden-js/src/lib.rs +++ b/oden-js/src/lib.rs @@ -77,6 +77,12 @@ impl From for Error { } } +impl From for Error { + fn from(e: std::str::Utf8Error) -> Self { + Error::ConversionError(e.to_string()) + } +} + pub type Result = core::result::Result; pub type ValueResult = core::result::Result; diff --git a/src/io.ts b/src/io.ts index e95fada6..7131bc94 100644 --- a/src/io.ts +++ b/src/io.ts @@ -6,6 +6,12 @@ import * as core from "io-core"; * @param path The path of the file to load. * @returns The contents of the file. */ -export function load(path: string): Promise { - return core.load(path); -} +export const load = core.load; + +/** + * Load the specified file into memory as a string. + * + * @param path The path of the file to load. + * @returns The contents of the file decoded from utf-8. + */ +export const load_string = core.load_string; diff --git a/src/script/io.rs b/src/script/io.rs index d508c040..ba3521fc 100644 --- a/src/script/io.rs +++ b/src/script/io.rs @@ -82,6 +82,24 @@ impl IoImpl { Ok(value) } + + fn load_string(&self, context: &ContextRef, path: &str) -> ValueResult { + let (value, promise) = context.new_promise()?; + + let path = path.to_string(); + self.thread_pool.execute(Box::new(move || { + let path = path; + + let result = resolve_path(&path, &[]).and_then(|p| std::fs::read(p)); + promise.resolve(move |ctx: &ContextRef| { + let result = result?; + let string = std::str::from_utf8(&result)?; + ctx.new_string(string) + }); + })); + + Ok(value) + } } pub struct IoAPI {} @@ -97,6 +115,13 @@ impl IoAPI { ctx.new_fn(move |ctx: &ContextRef, p: String| io.load(ctx, &p))?, )?; } + { + let io = io.clone(); + builder.export( + "load_string", + ctx.new_fn(move |ctx: &ContextRef, p: String| io.load_string(ctx, &p))?, + )?; + } builder.build("io-core")?; Ok(IoAPI {}) } diff --git a/types/io-core.d.ts b/types/io-core.d.ts index e5114f02..283b70df 100644 --- a/types/io-core.d.ts +++ b/types/io-core.d.ts @@ -1,3 +1,5 @@ // These are the functions exposed by the native IO module. // export function load(path: string): Promise; + +export function load_string(path: string): Promise;