summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBartek IwaƄczuk <biwanczuk@gmail.com>2023-02-06 16:20:20 +0100
committerGitHub <noreply@github.com>2023-02-06 16:20:20 +0100
commit34bfa2cb2c1f0f74a94ced8fc164e81cc91cb9f4 (patch)
tree618eb394954236649841ceba363542f6abf39cac
parentfd511d57550f43493695470acf9282aa044258e2 (diff)
refactor(npm): use per-thread package.json cache (#17644)
This commit adds a per-thread cache for `package.json` files. It's similar to what Node.js is doing.
-rw-r--r--ext/node/package_json.rs18
1 files changed, 18 insertions, 0 deletions
diff --git a/ext/node/package_json.rs b/ext/node/package_json.rs
index 5894b8831..e40448930 100644
--- a/ext/node/package_json.rs
+++ b/ext/node/package_json.rs
@@ -11,9 +11,15 @@ use deno_core::serde_json;
use deno_core::serde_json::Map;
use deno_core::serde_json::Value;
use serde::Serialize;
+use std::cell::RefCell;
+use std::collections::HashMap;
use std::io::ErrorKind;
use std::path::PathBuf;
+thread_local! {
+ static CACHE: RefCell<HashMap<PathBuf, PackageJson>> = RefCell::new(HashMap::new());
+}
+
#[derive(Clone, Debug, Serialize)]
pub struct PackageJson {
pub exists: bool,
@@ -58,6 +64,12 @@ impl PackageJson {
pub fn load_skip_read_permission(
path: PathBuf,
) -> Result<PackageJson, AnyError> {
+ assert!(path.is_absolute());
+
+ if CACHE.with(|cache| cache.borrow().contains_key(&path)) {
+ return Ok(CACHE.with(|cache| cache.borrow()[&path].clone()));
+ }
+
let source = match std::fs::read_to_string(&path) {
Ok(source) => source,
Err(err) if err.kind() == ErrorKind::NotFound => {
@@ -136,6 +148,12 @@ impl PackageJson {
imports,
bin,
};
+
+ CACHE.with(|cache| {
+ cache
+ .borrow_mut()
+ .insert(package_json.path.clone(), package_json.clone());
+ });
Ok(package_json)
}