简体   繁体   中英

Node.js require caching

I am really stuck by nodejs cache system. I have this structure for my project :

Project/
    apps/
        jobs_processor/
            app.js
            processors.js
            processors/
    libs/
        queue_manager.js

queue_manager.js require processors.js

var processors = require("../apps/jobs_processor/processors.js");

app.js require also processor.js

var processors = require("./processors.js");

If I take into account the documentation, I must have the same path may be to obtain the same object, is that right ? If so, how can I achieve that (have the same path) ?

Thanks.

EDIT:

If found a solution to my problem. Here is the first version of queue_manager.js file

var _ = require("lodash");

var Utils = require("./utilities");
var Processors = require("../apps/jobs_processor/processors");
var Logger = require("./logger");

var QUEUES_CACHE = {};

exports.createJob = createJob;
exports.getCacheObject = getCacheObject;

function createJob(name, data) {
  var cacheId = name.replace(/ /g, "_");

  Logger.info("Cache ID: " + cacheId);

  if (!QUEUES_CACHE[ cacheId ]) {
    _.each(Processors, function (processor) {
      Logger.debug("PROCESSOR NAME: " + processor.name);
      Logger.debug("JOB NAME: " + name);

      if (processor.name === name)
        QUEUES_CACHE[ cacheId ] = processor;
    });

    if (!QUEUES_CACHE[ cacheId ])
      throw new Error("Processor for job \"" + name + "\" not found.");
  }

  Logger.debug(Object.keys(QUEUES_CACHE));

  return QUEUES_CACHE[ cacheId ].queue.add(data);
}

function getCacheObject() {
  return QUEUES_CACHE;
}

And now the last version of the same file

var _ = require("lodash");

var Utils = require("./utilities");
var Logger = require("./logger");

exports.createJob = createJob;

function createJob(name, data) {
  var Processors = require("../apps/jobs_processor/processors");
  var processor;

  _.each(Processors, function (element) {
    Logger.debug("Processor name: " + element.name);

    if (element.name === name)
      processor = element;
  });

  return processor.queue.add(data);
}

Each time that i called createJob method, I require the processors module which is an array of each job processor that I have created.

Node.js will resolve the path before caching the module.
As long as your relative paths resolve to the same absolute path on disk, you're fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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