Skip to content

Commit

Permalink
feat(core): Add FsModuleLoader that supports loading from filesystem (d…
Browse files Browse the repository at this point in the history
…enoland#8523)

This commit adds `FsModuleLoader` to `deno_core`, which implements
`ModuleLoader` trait. It is used when creating a runtime that supports
module loading from filesystem.

Co-authored-by: Bartek Iwańczuk <[email protected]>
  • Loading branch information
magurotuna and bartlomieju committed Nov 27, 2020
1 parent a16adca commit b8d3caa
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions core/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub use crate::async_cell::RcRef;
pub use crate::flags::v8_set_flags;
pub use crate::module_specifier::ModuleResolutionError;
pub use crate::module_specifier::ModuleSpecifier;
pub use crate::modules::FsModuleLoader;
pub use crate::modules::ModuleId;
pub use crate::modules::ModuleLoadId;
pub use crate::modules::ModuleLoader;
Expand Down
45 changes: 45 additions & 0 deletions core/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,51 @@ impl ModuleLoader for NoopModuleLoader {
}
}

/// Basic file system module loader.
///
/// Note that this loader will **block** event loop
/// when loading file as it uses synchronous FS API
/// from standard library.
pub struct FsModuleLoader;

impl ModuleLoader for FsModuleLoader {
fn resolve(
&self,
_op_state: Rc<RefCell<OpState>>,
specifier: &str,
referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, AnyError> {
Ok(ModuleSpecifier::resolve_import(specifier, referrer)?)
}

fn load(
&self,
_op_state: Rc<RefCell<OpState>>,
module_specifier: &ModuleSpecifier,
_maybe_referrer: Option<ModuleSpecifier>,
_is_dynamic: bool,
) -> Pin<Box<ModuleSourceFuture>> {
let module_specifier = module_specifier.clone();
async move {
let path = module_specifier.as_url().to_file_path().map_err(|_| {
generic_error(format!(
"Provided module specifier \"{}\" is not a file URL.",
module_specifier
))
})?;
let code = std::fs::read_to_string(path)?;
let module = ModuleSource {
code,
module_url_specified: module_specifier.to_string(),
module_url_found: module_specifier.to_string(),
};
Ok(module)
}
.boxed_local()
}
}

#[derive(Debug, Eq, PartialEq)]
enum Kind {
Main,
Expand Down

0 comments on commit b8d3caa

Please sign in to comment.