DEV Community

Cover image for Create a backend in Javascript (part 2): NodeJS Module System
Eric The Coder
Eric The Coder

Posted on • Updated on

Create a backend in Javascript (part 2): NodeJS Module System

Here is a series of articles to help you create backend applications in Javascript.

Node.js is now a must, so it is essential for a developer to master it.

I will publish a new article every two days and little by little you will learn everything there is to know about Node.js

To not miss anything follow me on twitter: https://twitter.com/EricTheCoder_


NodeJS Module System

Writing code in a file is fine, but if your application need a lot of code, your file will quickly become too large.

This is why it is better to separate your code into several modules (file) in order to make the code reusable and much better structured.

here is an example

app.js

const name = 'Mike Taylor'

const greeting = function(name) {
    console.log(`Hello ${name}, welcome to NodeJS`)
}

greeting(name)
Enter fullscreen mode Exit fullscreen mode

It could be interesting to make the greeting module reusable. To do this we will place it in its own file called greeting.js

const greeting = function(name) {
    console.log(`Hello ${name}, welcome to NodeJS`)
}
Enter fullscreen mode Exit fullscreen mode

By default NodeJS does not allow to use this function from another module. To do this, you must indicate to the module which elements can be exportable:

const greeting = function(name) {
    console.log (`Hello ${name}, welcome to NodeJS`)
}

module.exports = greeting
Enter fullscreen mode Exit fullscreen mode

Note here the last line 'module.exports = greeting', this function allows the use of the greeting function from another module.

From app.js you can now load this module with the 'require' function

const greeting = require('./greeting.js')

const name = 'Mike Taylor'
greeting(name)
Enter fullscreen mode Exit fullscreen mode

The 'require' function will create a reference with the greeting module and place this reference in the const greeting variable (this variable could have been called another name than greeting)

Note that the function require ('./greeting.js') uses the path './' this allows to indicate to NodeJS that the module is in the same folder as our app.js file

Multiple exports

It is possible to export several elements with the function module.exports. Here is an example: person.js

const name = 'Mike Taylor'
const car = 'Ford Mustang'

module.exports = {name, car}
Enter fullscreen mode Exit fullscreen mode

Multiple exports is therefore done with an object that contains several elements.

const person = require('./ person.js')

console.log(person.name, person.car)
Enter fullscreen mode Exit fullscreen mode

Note that the 'person' variable does not point to the 'name' or 'car' directly, it points to the object that is exported. So to return its content we have to use 'person.name'

Multiple export (alternative syntax)

It is possible to export several elements with the function module.exports. Here is an example: person.js

const name = 'Mike Taylor'
const car = 'Ford Mustang'

module.exports.name = name
module.exports.car = car
Enter fullscreen mode Exit fullscreen mode

The usage remains the same:

const person = require('./ person.js')

console.log(person.name, person.car)
Enter fullscreen mode Exit fullscreen mode

It is also possible to use deconstruction

const {name, car} = require('./ person.js')

console.log(name, car)
Enter fullscreen mode Exit fullscreen mode

The 'require' function executes the module

When executing the require function, the module is executed immediately. here is an example

// hello.js

const hello = function() {
    console.log('Hello World')
}

modules.exports = hello
Enter fullscreen mode Exit fullscreen mode
// app.js

const hello = require('./ hello.js')
Enter fullscreen mode Exit fullscreen mode

As soon as NodeJS executes this line, the hello module is also executed. In this example the module only does an export but if the module contained code it would be executed, here is an example

// hello.js

const hello = function() {
    console.log('Hello World')
}

console.log('Hello Node!')

modules.exports = hello
Enter fullscreen mode Exit fullscreen mode
// app.js

const hello = require('./ hello.js')

Hello()
Enter fullscreen mode Exit fullscreen mode

If you launched app.js, you will see that it will display 'Hello Node!' before the 'Hello World' because as mentioned, the 'require' executes the module.

Take this fact into account when you create your modules in order to avoid unwanted behavior.

Conclusion

That's all for today, follow me on twitter: https://twitter.com/EricTheCoder_ to be notified of the publication of the next article (within two days).

Top comments (13)

Collapse
 
beauspot profile image
Iyere Handsome(Beau) Omogbeme

There is a bug on your code in the module app.js. You are exporting the greeting function but then when you want to import it you don't use the greeting function in another module rather you say require('app.js'), not 'greeting'. if you run the code It would throw an error stating that the module greeting cannot be found. greeting() is not a module rather it is a function that is exported from a module to another. I would upload Images for you to see what I am saying.

Collapse
 
beauspot profile image
Iyere Handsome(Beau) Omogbeme

This code would return an error stating that the module cannot be found

Collapse
 
salehmubashar profile image
Saleh Mubashar

Thanks,
Can you also make one for how to connect node with database and use node,react and a databse together . thanks

Collapse
 
ericchapman profile image
Eric The Coder

The database part in almost done but I am not sure I will do the React Part.

Collapse
 
salehmubashar profile image
Saleh Mubashar

oh okay, thx

Collapse
 
jitendradadhich profile image
Jitendra Dadhich

Thanks for sharing

Collapse
 
ericchapman profile image
Eric The Coder

You're welcome !

Collapse
 
abdullmng profile image
abdullmng

I look forward to learning from you

Collapse
 
mayarabtm profile image
Mayara B.

Cool, thanks for sharing.

Collapse
 
merite15 profile image
Merite15

Are you writing an article about express js

Collapse
 
ericchapman profile image
Eric The Coder

Yes ExpressJS articles are coming right after NodeJS.

Many of them are already written.

Collapse
 
andycharles6 profile image
andycharles6

Can you also cover Adonisjs in an article? I think it can be used as a reference for batteries included framework.

Express- A simple and small Node framework
Adonisjs - Batteries included and more structured framework.

Thanks. Keep up the great work

Collapse
 
idsudeep profile image
sudeep

Thank you