diff options
author | Yusuke Tanaka <yusuktan@maguro.dev> | 2020-11-28 06:45:38 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-11-27 22:45:38 +0100 |
commit | b8d3caa5d586c6957866261bd5f51c85ad3a2c91 (patch) | |
tree | 456b8a98020b800a9165fd11745d518d920aad64 | |
parent | a16adca06b60141c04078a496ac48581bf755e4a (diff) |
feat(core): Add FsModuleLoader that supports loading from filesystem (#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 <biwanczuk@gmail.com>
-rw-r--r-- | core/lib.rs | 1 | ||||
-rw-r--r-- | core/modules.rs | 45 |
2 files changed, 46 insertions, 0 deletions
diff --git a/core/lib.rs b/core/lib.rs index 34bd25bcb..732c5d745 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -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; diff --git a/core/modules.rs b/core/modules.rs index c12f900bb..ffae3a476 100644 --- a/core/modules.rs +++ b/core/modules.rs @@ -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, |