[oden] IO: Load Strings

It's useful. The stock JS way is bad.
This commit is contained in:
John Doty 2023-07-08 17:55:37 -07:00
parent 89045ccbcc
commit 17c701a7d6
4 changed files with 42 additions and 3 deletions

View file

@ -77,6 +77,12 @@ impl From<std::io::Error> for Error {
} }
} }
impl From<std::str::Utf8Error> for Error {
fn from(e: std::str::Utf8Error) -> Self {
Error::ConversionError(e.to_string())
}
}
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T> = core::result::Result<T, Error>;
pub type ValueResult = core::result::Result<Value, Error>; pub type ValueResult = core::result::Result<Value, Error>;

View file

@ -6,6 +6,12 @@ import * as core from "io-core";
* @param path The path of the file to load. * @param path The path of the file to load.
* @returns The contents of the file. * @returns The contents of the file.
*/ */
export function load(path: string): Promise<ArrayBuffer> { export const load = core.load;
return core.load(path);
} /**
* 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;

View file

@ -82,6 +82,24 @@ impl IoImpl {
Ok(value) 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 {} pub struct IoAPI {}
@ -97,6 +115,13 @@ impl IoAPI {
ctx.new_fn(move |ctx: &ContextRef, p: String| io.load(ctx, &p))?, 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")?; builder.build("io-core")?;
Ok(IoAPI {}) Ok(IoAPI {})
} }

2
types/io-core.d.ts vendored
View file

@ -1,3 +1,5 @@
// These are the functions exposed by the native IO module. // These are the functions exposed by the native IO module.
// //
export function load(path: string): Promise<ArrayBuffer>; export function load(path: string): Promise<ArrayBuffer>;
export function load_string(path: string): Promise<string>;