0

I am learning Node.js following a Udemy course, and the code below would maintain the data in the 'products' array when the module in exported in different files (although the instructor doesn't give any explanation about it).

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

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?

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;
David Ciocoiu
  • 113
  • 1
  • 2
  • 6

1 Answers1

1

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

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

If you require a module which exports an object (like router) then you get the same object each time. Since it is the same object, the products variable that is closed over by the module is the same variable, so it you are accessing the same array.

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?

That wouldn't use require so said caching wouldn't apply.

Reloading the page also completely restarts any JavaScript programs embedded in that page, so it would reset to whatever the source code said even if that wasn't the case.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335