Node.js 导出模块维护数据

Node.js exported modules maintain data

我正在按照 Udemy 课程学习 Node.js,当模块导出到不同的文件中时,下面的代码将维护 'products' 数组中的数据(尽管讲师没有给出关于它的任何解释)。

模块如何保持其状态,是否只是因为它是用 Node 导出并用 express.js 处理的?

还有一个静态 js 文件会发生什么,它只包含一个要调用(例如)到 HTML 文件中的脚本,这仍然会保持其状态还是每次都会重新加载html 页面重新加载了吗?

const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();

const products = [];


router.get('/add-product', (req, res, next) => {
  res.sendFile(path.join(rootDir, 'views', 'add-product.html'));
});


router.post('/add-product', (req, res, next) => {
  products.push({title: req.body.title});
  res.redirect('/');
});

exports.routes = router;
exports.products = products;

How come the module maintains its state, is it just because it is exported with Node and worked upon with express.js?

参见 the documentation for require. The values exported from modules are, by default, cached. Objects are handled by reference

如果您需要一个导出对象的模块(如 router),那么您每次都会得到 相同的 对象。因为是同一个对象,模块关闭的 products 变量是同一个变量,所以你访问的是同一个数组。

Also what would happen to a static js file which would contain just a script to be called (say for instance) into an HTML file, would this still maintain its state or would it be reloaded every time the html page is reloaded?

那不会使用 require 所以说缓存不适用。

重新加载页面也会完全重新启动该页面中嵌入的任何 JavaScript 程序,因此即使不是这种情况,它也会重置为源代码所说的任何内容。