From b8d3caa5d586c6957866261bd5f51c85ad3a2c91 Mon Sep 17 00:00:00 2001 From: Yusuke Tanaka Date: Sat, 28 Nov 2020 06:45:38 +0900 Subject: feat(core): Add FsModuleLoader that supports loading from filesystem (#8523) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- core/lib.rs | 1 + core/modules.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) 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>, + specifier: &str, + referrer: &str, + _is_main: bool, + ) -> Result { + Ok(ModuleSpecifier::resolve_import(specifier, referrer)?) + } + + fn load( + &self, + _op_state: Rc>, + module_specifier: &ModuleSpecifier, + _maybe_referrer: Option, + _is_dynamic: bool, + ) -> Pin> { + 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, -- cgit v1.2.3