简体   繁体   English

Javascript - 如何将相同的 JSON(或替代)文件加载到 node.js 和浏览器中

[英]Javascript - how to load the same JSON (or alternative) file into both node.js and browser

I'm looking to load into memory a JSON file (or a.js file with an object in it) into both a node script and into the browser.我希望将 memory 文件(或带有 object 的 a.js 文件)加载到节点脚本和浏览器中。 Is there any clean and pure JS way to do this without having a separate file for each?是否有任何干净和纯粹的 JS 方法可以做到这一点,而无需为每个单独的文件?

The file simply holds properties about things that are used on both client and server side, the goal is when I need to change some property it will reflect on both the client (javascript) and the server (node).该文件仅包含有关客户端和服务器端使用的事物的属性,目标是当我需要更改某些属性时,它将反映在客户端(javascript)和服务器(节点)上。 The does not need to be updated while running, and ideally should be loaded and cached on page load and script start respectively.运行时不需要更新,理想情况下应该分别在页面加载和脚本启动时加载和缓存。

I've tried using a.json file which made it easy to require in node, but in the browser the only solutions I saw used packages or some sort of over complicated api that seemed too overkill for my use (although this might be my only option).我试过使用一个 .json 文件,这使得它很容易在节点中使用,但在浏览器中我看到的唯一解决方案是使用包或某种过于复杂的 api,这对我的使用来说似乎太过分了(尽管这可能是我唯一的选项)。 If i store the properties as a.js file with an object defined in it it's easy to load in browser, but not in node without module.exprots.如果我将属性存储为 a.js 文件,其中定义了 object,则很容易在浏览器中加载,但在没有 module.exprots 的节点中加载。

Seems inconvenient that I can't easily do this, especially when it's a just a small JSON object with item properties.我不能轻易做到这一点似乎很不方便,尤其是当它只是一个带有项目属性的小型 JSON object 时。

Any help is appreciated!任何帮助表示赞赏!

Just make the file public, and use it in front and backend.只需将文件公开,并在前端和后端使用它。

Asuming you use epxress.假设您使用 epxress。

app.use(express.static('./')); //Use static folder

But note sharing files can be inscure if you have senstive information, but you already know that.但是,如果您有敏感信息,请注意共享文件可能会变得不安全,但您已经知道了。

Edit编辑

You say it is not the problem, in the comments.你说这不是问题,在评论中。 I say then you have to make some sort of endpoint to export this array.我说那你必须做某种端点来导出这个数组。 Do this:做这个:

const object = {
   // You object here
}

app.get('/route', (req, res) => {
   res.json(object);
}

Client:客户:

fetch('/route').then(res => res.json()).then(data => {
    // You have access to the data, here.
})

Like this you can use the object on both the backend and frontend.像这样,您可以在后端和前端使用 object。

Altough I suspect there is a way to do this using also static folder.尽管我怀疑还有一种方法可以使用 static 文件夹来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM