I'm trying to structure my Nodejs project by component, following this Nodejs best practice repo.
So my question is, how can i place an Order and update the Product items left in db. Should i use ProductsService inside Order component.
Have anyone already implemented this approach? Can you give me some example.
Thank you!
If ProductsService contains a method or function that is exported, you should use this exported function inside of the Order component to update the products in the database.
Example
mymodule.js
// exported function
const myFunction = function(foo) {
if(foo) {
return bar;
}
}
module.exports = myFunction;
index.js
const myModule = require('./mymodule.js');
// using the function
myModule(value);
Related
I want to have a global script that I can include system wide for some helper files.
This is the helper file (helper.js):
async function hasStock() {
}
// Export it to make it available outside
module.exports.hasStock = hasStock;
But now the problem, I have a model that I give in the index.js, the model is only available there:
app.use('/api/parts', require('./routes/part.js')(app, models));
But I also need that model (models) at my helper.js file.
So I thought I need to do this in part.js (from /api/parts):
module.exports = function (app, models) {
require("../helpers/helper.js")(models);
}
But that isn't also good I think. What is a good solution to include the models (models object only available in the index.js) and to use this system wide in helpers.js?
You should try to export the function hasStock by following method ,
In your helper.js file
const anyObjectName = {
hasStock : async function hasStock {
}
}
//like this export , you can use this object and it's function anywhere .
module.exports = anyObjectName;
In your part.js (from /api/parts):
var anyObjectName = require('../helpers/helper.js');
//now you can access the hasStock function in part.js file like
anyObjectName.hasStock();
Hope it is useful for your and solves your problem .
Everyone I'm beginner in NODE.JS i'm using module.exports function inside that I have written hello function in it.I tried to import from other file.but it's not working.Can anyone solve this problem.Thanks in advance...
index.js
module.exports=function(){
hello:(data)=>{
return "Good night" +data;
}
}
trail.js
const index=require('./index');
const e=new index();
console.log(e.hello("abc"));
When you're using a function as a constructor, creating new objects from it, you'll have to reference each of those objects with this to assign their properties:
module.exports=function(){
this.hello = (data) => {
return "Good night" +data;
};
}
The syntax <identifier>: has different meanings depending on its placement/surroundings. When used within a function body, at the start of a statement, it only defines a label. To have it define a property, it would have to be used within an object initializer.
I found the solution slightly we have to change the code in index.js.In ES6 Functional constructors are available.we should use this keyword this keywords refers current class objects.because In javascript Functions are first class Objects.correct me If I'm wrong. post the answer if anyone knows Others solution are also always welcome....
Index.js
module.exports=function(){
this.hello=(data)=>{
return "Good night" +data;
}
}
Trail.js
const index=require('./index');
const e=new index();
console.log(e.hello("abc"));
you can also use it this way:
module.exports=function(data){
return "Good night" +data;
}
const temp = require('./index');
console.log(temp('demo developer'));
I dont know what is the correct desicion you tring to find out, but may be you would like to go this way:
index.js:
exports.hello = data => {
return 'Good night ' + data;
};
trail.js:
const e = require('./index');
console.log(e.hello('Jhonny'));
I have multiple different files broken out like so:
index.js
utils.js
ClassA/
index.js
base.js
utils contains a number of utility functions used everywhere. ClassA/index.js contains the constructor for ClassA as well as requires base.js, then exports ClassA. Base.js exports prototype methods for ClassA. Here is basically what they look like:
//ClassA/index.js
function ClassA () {
//constructor stuff
}
ClassA.prototype.constructor = ClassA;
require('./base')(ClassA);
module.exports = ClassA;
//ClassA/base.js
module.exports = ClassA => {
ClassA.prototype.aMethod = function () {
log('hello');
}
//utils.js
module.exports = {
log : function (logText) {
//dostuff
}
}
So my problem is that I cannot access the log function from within methods in ClassA/base.js. If I set const log = require('../utils').log at the top of the file, it doesn't work. It also doesn't work if I place that same line of code within the exports but outside of the method definitions, however it does work if I place it within the method itself (as expected, but this would mean replicating every require statement in any method in which it's needed). Is there any way around using this messy and repetitive route?
It was an issue with cyclic dependencies. I changed 'log' to be a method of ClassA and this resolved the issue. Thanks to Francois P. for pointing me in the right direction.
Hi I found a framework where they use a lot this pattern.
exports.install = function(){
//code
}
but usually you see this pattern in nodejs
module.exports = {
//code
}
Is this the same thing or is this something else ?
exports is the object corresponding to module.exports before you do anything to it. I think it's due to some legacy code, but basically folks use module.exports if they want to replace the whole object with their own object or a function, while they use exports if they just want to hang functions off the module. It's a little confusing at first, but essentially exports.install just means that calling code would do something like:
const mod = require('that-module');
mod.install(params, callback); // call that function
The framework you're looking at is probably using it as part of a bootstrapping process, afaik it doesn't have significance to the node engine itself.
Yes, it is the same thing. You can use one of 2 ways to setup your code.
The different thing is memory. They point to same memory. You can think exports like a variable and you can not use this way to export your module:
Given this module:
// test.js
exports = {
// you can not use this way to export module.
// because at this time, `exports` points to another memory region
// and it did not lie on same memory with `module.exports`
sayHello: function() {
console.log("Hello !");
}
}
The following code will get the error: TypeError: test.sayHello is not a function
// app.js
var test = require("./test");
test.sayHello();
// You will get TypeError: test.sayHello is not a function
The correct way you must use module.exports to export your module:
// test.js
module.exports = {
// you can not use this way to export module.
sayHello: function() {
console.log("Hello !");
}
}
// app.js
var test = require("./test");
test.sayHello();
// Console prints: Hello !
So, it just is style of developer.
I have read the details on NodeJS site : https://nodejs.org/api/modules.html. I don't understand how modules work, and what are the minimal steps for creating a module, and how npm can help me.
How can I create a module?
How do I use a module?
What does putting it on npm mean?
Note: this is a self answered question, with the purpose of sharing knowledge as a canonical.
You can create a NodeJS module using one line of code:
//mymodule.js
module.exports = 3;
Then you can load the module, by using require:
//app.js
require('./mymodule.js')
I added './' because it is a module of one file. We will cover it later.
Now if you do for example:
var mymodule = require('./mymodule.js');
console.log(mymodule); // 3
You can replace the number 3, with a function, for example:
//mymodule.js:
module.exports = function () {
console.log('function inside the module');
};
Then you can use it:
var mymodule = require('./mymodule.js');
mymodule();
Private variables:
Every variable you define inside A module will be defined only inside it:
//mymodule.js
var myPrivateVariable = 3;
publicVariable = 5; // Never user global variables in modules
//It's bad-pracrtice. Always add: var.
module.exports = function() {
// Every function of the module can use the private variables
return myPrivateVariable++
};
//app.js
var mymodule = require('./mymodule.js');
console.log(mymodule()); // return 3
console.log(mymodule()); // return 4
Reuse modules:
One more thing you need to know about NodeJS modules, is that if you use the same module twice(require it), it will return the same instance, it will not run in twice.
for example:
//app.js
var mymodule1 = require('./mymodule.js');
var mymodule2 = require('./mymodule.js');
console.log(mymodule1()); //return 3
console.log(mymodule2()); //return 4 (not 3)
console.log(mymodule1()); //return 5
As you see in the example below, that private variable is shared between all the instances of the module.
A module package
If your module contain more than one file, or you want to share the module with others, you have to create the module in separate folder, and create a package.json file for the module.
npm init will create package.json file for you.
For modules, there are 3 required parts:
package.json
{
"name" : "You module name",
"version" : "0.0.3"
}
Now, you can publish the module, using npm publish. I recommend you publish all your modules to github as well, then the module will be connected to your github page.
What you publish to NPM will be accessible by everyone. So never publish modules that contain private data. For that you can use private npm modules.
Next steps
Modules can return more than one function or one variable. See this samples in which we return an object.
module.exports.a = function() {
// ..
};
module.exports.b = function() {
// ..
};
// OR
myObj = {
a:3,
b:function() {
return this.a;
}
};
module.exports = myObj;
More info:
Read about package.json files
Versioning in you modules best practice
More best practive for NodeJS modules
Private modules, using private npm
Related Questions:
What is the purpose of Node.js module.exports and how do you use it?
module.exports vs exports in Node.js
Creating module in node.js is pretty simple!!!
You may consider module as a set of functionalities you can use in other code by simply just requiring it.
for eg:Consider a file functional.js having the content:
function display(){
console.log('i am in a display function');
}
module.exports = display;
Now just require it in any other module like:
var display = require('./functional');
display()
Output:i am in a display function
Similarly you can do:
var exports = module.exports = {};
exports.display = function(){
console.log('i am in the display function');
}
or you do the same for objects like:
var funObj = {
hello:function(){
console.log('hello function');
},
display:function(){
console.log('display function');
}
};
module.exports = funObj;
There are two main ways for wiring modules. One of them is using hard coded dependencies, explicitly loading one module into another using a require call. The other method is to use a dependency injection pattern, where we pass the components as a parameter or we have a global container (known as IoC, or Inversion of Control container), which centralizes the management of the modules.
We can allow Node.js to manage the modules life cycle by using hard coded module loading. It organizes your packages in an intuitive way, which makes understanding and debugging easy.
Dependency Injection is rarely used in a Node.js environment, although it is a useful concept. The DI pattern can result in an improved decoupling of the modules. Instead of explicitly defining dependencies for a module, they are received from the outside. Therefore they can be easily replaced with modules having the same interfaces.
Let’s see an example for DI modules using the factory pattern:
class Car {
constructor (options) {
this.engine = options.engine
}
start () {
this.engine.start()
}
}
function create (options) {
return new Car(options)
}
module.exports = create