0

Good time to all. Recently started learn javascript and experiment with node server coding and now really can't understand what is happening..

I have classic app.js

...
var view = require('./routes/view');
...
app.use('/mix', view);
...

And this is my view.js

var express = require('express');
var router = express.Router();
var moment = require("moment");

var DB = require('../modules/mysql')

/*  */
router.get('/:mixId', (req, res, next) => {

  /** set defaults */
  let config = require('../cfg/hbs.json'); // config load (see example below)
  var page = "pages/viewFail",
    alert = {};

  /** select info about mix */
  DB.query('SELECT startTS, targetAdr, received FROM mixes m WHERE name=?', [req.params.mixId], (err, results) => {

    /** if not exist */
    if (results.length === 0) {
      alert = { // danger alert
        "color": "danger",
        "text": "this mix does not exist"
      }
    }
    /** exist */
    else {

      var mix = {
        "adr": results[0].targetAdr,
        "received": results[0].received,
        /** calculate endin in minudes */
        "endin": parseInt(120 - moment.duration(moment().diff(moment(results[0].startTS))).asMinutes()),
      }

      /** check end time and ballance. if no transactions and time ends - exit */
      if (mix.endin <= 0 && mix.received <= 0) {
        alert = {
          "color": "danger",
          "text": "this mix does not exist"
        }
      } else {

        if (mix.received == 0) {
          page = 'pages/viewStart'
        } else {
          config.meta.js.push("/js/viewEnd.js"); /** add common page js {} */
          page = 'pages/viewEnd'

          console.log(config.meta)
          console.log("\n------------\n")

        }
      }
    }


    /** send response */
    res.render(page, {
      layout: 'layout',
      meta: config.meta,
      alert: alert,
      mix: mix,
    });
  });
});

module.exports = router;

Here is my config file:

{
  "meta": {
    "title": "test partials",
    "css": [
      "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css",
      "/css/c.css"
    ],
    "js": [
      "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js",
      "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js",
      "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
    ],
    "tmp": [
      "https://code.jquery.com/jquery-3.2.1.slim.min.js"
    ]

  }
}

And the problem is: when I restart page meta.js add time after time and result is:

{ title: 'test partials',
  css: 
   [ 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css',
     '/css/c.css' ],
  js: 
   [ 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js',
     'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js',
     'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js',
     '/js/viewEnd.js',  // ??????
     '/js/viewEnd.js',  // ??????
     '/js/viewEnd.js' ],// ??????
  tmp: [ 'https://code.jquery.com/jquery-3.2.1.slim.min.js' ] }

So what am I doing wrong?

U Rogel
  • 1,893
  • 15
  • 30
gooftime
  • 53
  • 2
  • 6
  • Forgot to said that im using handlebars and in my template code is: {{#each meta.js}} {{/each}} But don't think this is mattered – gooftime Nov 20 '17 at 15:09

1 Answers1

1

Consider the following:

let config1 = require('../cfg/hbs.json');
let config2 = require('../cfg/hbs.json');

console.log(config1 === config2);

This will log the value true, meaning that config1 and config2 refer to the exact same object.

The reason for this is that require performs caching. It will only read the file the first time. Subsequent calls to require the same file will just return the cached object.

This is what's happening in your code. Each time the route is called it's pulling in the same config object and then pushing an extra entry into the same array.

There are several ways to resolve this. One simple solution is to take a deep copy of the object by JSON encoding it:

let config = JSON.parse(JSON.stringify(require('../cfg/hbs.json')));
skirtle
  • 27,868
  • 4
  • 42
  • 57
  • Thansk a lot. Found another solution here: https://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate, but your is prettier. – gooftime Nov 20 '17 at 15:45