Using require without export

后端 未结 3 1243
轻奢々
轻奢々 2021-02-05 01:26

I have this code (which works perfectly well) which I\'ve borrowed from an online resource:

var express = require(\'express\');
var bodyParser = require(\'body-p         


        
3条回答
  •  甜味超标
    2021-02-05 02:03

    When you call require the module is loaded and executed. So you have a connected mongoose. Actually require makes a function that your entire module code injected there and finally run.

    Now, if you want to reuse variables created in modules you should export that. Like :

    //cache.js
    var redis  = require("redis");
    
    var redisClient  = redis.createClient(process.env.CACHE_PORT, process.env.CACHE_URL);
    redisClient.auth(process.env.CACHE_PASS);
    
    redisClient.on("ready", function () {
      console.log("Cache is connected");
    });
    
    module.exports = redisClient;
    

提交回复
热议问题