Friday, 26 May 2017

Using module within module in NodeJS

I'm fairly new to nodejs. Writing my first application. I'm pretty used to php.

In order to keep code organized and clean, i always write functions in separate files and include them as required in php.

However, in nodejs i've had to require them like i would require a module. For example.

functions.js

module.exports = {
check_db : function(key){

},

check_cache : function(key){
    memcached.get(key,function(err, data){
        console.log(data);
    });
},

};

Included that in the main app like so

// Establish connection with cache and database
const mysql = require('mysql2');
const Memcached = require('memcached');
const memcached = new Memcached('localhost:11211');
const bb = require('bot-brother');

//Load the database cache functions
const dbc = require("./functions");
dbc.check_cache(123);

Now i can access the functions from dbc from the main app file, but i cannot use modules that have been required in the main app from the functions file. I get an error that memcached is not defined.

How can i go about solving this?



via Marshall Mathews

No comments:

Post a Comment