Node JS, exporting a class and cosumin it with different name - node.js

I'm using Node v14.4.0. I created a file and named it 'dao.js'. The file includes the following:
class AppDAO {
// some constructor and functions
}
module.exports = AppDAO
In my app.js file I load it using
const dao = require('./dao');
const db = new dao();
It works fine, but I don't know why, shouldn't I use the class name as I set it, "AppDAO", instead of "dao"?
This link as well as other links, do not help me in understanding how require modules works.
Is there something that I am missing?

You can do this
file dao.js
class AppDAO {
// some constructor and functions
}
exports.AppDAO = AppDAO;
and in app.js
const dao = require('./dao');
const db = new dao.AppDAO();

You are exporting the class from the file you are requiring, so you have to write it like this.
const dao = require('./dao');
const db = new dao.AppDAO();

Related

Node js - Issue with my syntax in require(module) . When to use {} and when not to use {} in require('module')

I have a query with the syntax in the require statement. Please refere the sample code below.
const nodemailer = require("nodemailer");
const {google} =require('googleapis');
const {OAuth2}=google.auth;
Some times , I see sample codes which use
const {<variable>} = require('moduleName')
Other times, I see like below
const <variable> = require('moduleName')
What is the difference between them?
Thanks in Advance.
Grateful to the Developers Community.
So, you use { } in this context when you want to do object destructuring to get a property from the exported object and create a module-level variable with that same name.
This:
const { google } = require('googleapis');
is a shortcut for this:
const __g = require('googleapis');
const google = __g.google;
So, within this context, you use the { google } only when you want the .google property from the imported module.
If you want the entire module handle such as this:
const nodemailer = require("nodemailer");
then, you don't use the { }. The only way to know which one you want for any given module is to consult the documentation for the module, the code for the module or examples of how to use the module. It depends entirely upon what the module exports and whether you want the top level export object or you want a property of that object.
It's important to realize that the { } used with require() is not special syntax associated with require(). This is normal object destructuring assignment, the same as if you did this:
// define some object
const x = { greeting: "hello" };
// use object destructuring assignment to create a new variable
// that contains the property of an existing object
const { greeting } = x;
console.log(greeting); // "hello
When you import the function with {}, it means you just import one function that available in the package. Maybe you have've seen:
const {googleApi, googleAir, googleWater} = require("googleapis")
But, when you not using {}, it means you import the whole package, just write:
const google = require("googleapis")
So, let say when you need googleApi in your code. You can call it:
google.googleApi

How to set global modules in multiple node.js files

I have a project which i'm working on, but i realised it was over 2000 lines and wanted to split it up into different files for different group of functions. eg. send message and read message functions are in message.js. The problem is that i need alot of modules in each of the files and if i create an instance of the module, i will need to create a new instance in another file, but i want to use the same instance!
I've tried module.exports = { ... } and exports.function() to pass the modules and instances to other files but sometimes it says that the function does not exist.
For example in my app.js file:
const module = require('module')
instance = new module()
const message = require('./message.js')
message.passModule(instance)
And in my message.js file:
let module-instance
exports.passModule = function(instance) {
module-instance = instance
}
module-instance.doSomething()
So, how could I have all the modules to be available in all the files, but only declare them in one, and how do I get the instance I made in one File to be able to be used in the other Files?
Some library file
singleton/file.js
const someDependency = require('some-module');
class Singleton {
method() {
...
return someDependency.someFunctionality();
}
...
}
module.exports = new Singleton();
Someplace where you want to use your singleton
const singleton = require('singleton/file');
singleton.method();

How to get properties defined outside of module.export from require object

I am struggling to get const properties define outside of module.exports from the object where I am using that module. here is simple example:
ServiceX.js
const _ = require('lodash');
module.exports = {
testFirstName: function () {
console.log('Nodics');
}
}
ServiceY.js
const utils = require('utils');
module.exports = {
testLastName: function () {
console.log('framework');
}
}
now if I import both file via require and merging via _.merge(). Output file contain both of the methods, but it doesn't contain any of the const variable define outside exports.
let combined = _.merge(require('ServiceX'), require('ServiceY'));
writing this combined to the third file some this MyService
even if I print this combined object via console.log(combined), I get only both functions, not const properties.
Use case I have:
I have n-number of files in different location, I need to read files, merge all and create a new file with merged content.
Please help me,
Thanks
A problem here is that a service currently looks like:
const _ = require('lodash');
module.exports = {
testFirstName: function () {
console.log('Nodics');
}
}
And the reason for that is that if you read all files and concatenate the result then module.exports will be overwritten by the last read file.
But if it instead looked like:
const _ = require('lodash');
module.exports.testFirstname = function () {
console.log('Nodics');
}
You could pull it off by doing fs.readFileSync() on all your services and concatenate the result.
You could also do it as a build command, rather than in code:
cat service*.js > combined.js
You will most likely run into other problems, since if one service uses const _ = require('lodash') and another is doing the same you will try to redefine a const variable.
To get around this you could move have to move your requires into another scope, so they don't conflict at file level scope.

Passing a parameter trough require-module to ES6 class in Nodejs

I am learning to use ECMAScript6 -styled classes in NodeJS (7.7.3). I have used this kind of programming style:
//app.js
var forecastHandler = require('./forecastHandler.js');
//forecastHandler.js
class ForecastHandler {
constructor() {}
}
module.exports = new ForecastHandler()
It has worked well until now, because I have to pass parameters to module.
//app.js
var forecastHandler = require('./forecastHandler.js')(3600);
//forecastHandler.js
class ForecastHandler {
constructor(cacheUpdateDelay) {}
}
module.exports = new ForecastHandler(cacheUpdateDelay)
I got this error: ReferenceError: cacheUpdateDelay is not defined.
Can I pass the parameter to ForecastHandler-module using ES6 styled classes and creating an object at module.exports? If I only export the class and create the object in app.js, code works, but it's syntax is ugly.
//app.js
var forecastHandlerClass = require('./forecastHandler.js');
var forecastHandler = new forecastHandlerClass(3600);
//forecastHandler.js
module.exports = ForecastHandler
EDIT: better examples
module.exports = new ForecastHandler(cacheUpdateDelay)
The trouble with this code is that it initialises the object when the code is first run.
require('./forecastHandler.js') means "execute all the code in forecastHandler.js and give me the exports object. This means that the JS engine tries to run new ForecastHandler(cacheUpdateDelay) when there is no cacheUpdateDelay created.
The simple way to do this is the one you provide. Load the class, then try to make a new instance of it. If you really want to one-line it, you can do this in app.js:
var forecastHandler = new (require('./forecastHandler.js'))(3600);
There are various other ways you could do this. The simplest involve not exporting a class but a function.
For instance, you could do this in your module file:
module.exports = cacheUpdateDelay => new ForecastHandler(cacheUpdateDelay);
// OR
module.exports = function(cacheUpdateDelay) {
return new ForecastHandler(cacheUpdateDelay);
};

Access variable in main node file from an imported file

//in app.js
var x = require("x.js");
var instanceX = new x();
require("./Weather")();
//in Weather.js
instanceX.getName();
In this case instanceX wouldn't exist when referenced from Weather.js. How do I make instanceX accessible in Weather.js?
There are a number of different ways to approach this in module design. One simple way is to just pass the variable to the weather.js constructor:
//in app.js
var x = require("x.js");
var instanceX = new x();
require("./Weather")(instanceX);
//in Weather.js
var instanceX;
module.exports = function(ix) {
instanceX = ix;
}
// then elsewhere in the module
instanceX.getName();
I refer to this as the "push" model because you're pushing things to the module that you want to share with it.

Resources