【问题标题】:JavaScript - reading JSON file with require gives different result than fs.readFileSyncJavaScript - 使用 require 读取 JSON 文件的结果与 fs.readFileSync 不同
【发布时间】:2019-11-01 19:26:00
【问题描述】:

我遇到了一个问题,让我觉得我缺少关于 require 在 JavaScript 中的工作方式的一些东西。基本上,如果我使用 require 读取 JSON 文件,我得到的结果与使用 fs.readFileSync 不同。

我从一个包含以下内容的 JSON 文件开始:

{"text":"old text"}

我首先使用requirefs.readFileSync 读取文件,并得到相同的结果。然后我用fs.writeFileSync 更新文件并用requirefs.readFileSync 再次读取文件,但更新后我得到不同的结果。

请务必注意,我需要来自函数内部的文件。我希望这会在每个函数调用中单独导入文件,但这显然不是正在发生的事情。只是想知道是否有人可以准确地解释发生了什么。

const fs = require('fs');
const textPath = './test.json';

const oldTextJSON = getText();  // prints as "old text"
const oldTextRead = JSON.parse(fs.readFileSync(textPath)).text;  // prints as "old text"

fs.writeFileSync(textPath, JSON.stringify({
  text: "new text"
}));

const newTextJson = getText();  // prints as "old text"
const newTextRead = JSON.parse(fs.readFileSync(textPath)).text;  // prints as "new text"

function getText() {
  return require(textPath).text;
}

【问题讨论】:

  • 需要缓存结果。多次调用 require 不会重新读取文件。
  • @MarkMeyer 是对的,只是我更喜欢以不同的方式思考它。 Require 不读取文件,它导入节点模块。以及如何导入节点模块?一次加载到内存,然后注入到所有地方。
  • 好的,我想这在多个文件需要一个文件时更明显 - 在所需文件的顶部添加 console.log 不会导致多次记录同一件事。但是,在大多数情况下,要么 1) require 用于另一个文件的顶部,它更明显地保存在内存中,要么 2) require 语句的结果不会改变。无论哪种方式,这都是有道理的。谢谢。

标签: javascript node.js json require fs


【解决方案1】:

希望这一行能说明require的特点。

const path = require("path");


const filepath = path.resolve(textPath);
delete require.cache[filepath];

无论您调用多少次,基本上都需要从 缓存 中读取。

【讨论】:

  • 所以delete require.cache[filepath] 在这里什么都不做?在函数中 require(textPath).text 之前添加时,它似乎没有任何改变。
  • 它会删除需要的缓存。然后如果你再次需要,它需要新的文件内容
猜你喜欢
  • 2015-06-28
  • 2016-05-25
  • 1970-01-01
  • 2019-09-14
  • 2020-08-12
  • 2016-04-25
  • 2019-03-27
  • 2016-01-13
  • 2018-11-02
相关资源
最近更新 更多