In the field of programming, functional modules are self-contained unit, can be shared and reused across projects. They make life easier for developers, because we can use it to increase the functionality of the application, without having to personally write these functions. It also allows us to organize and decoupled code to make the application easier to understand, debug and maintain.
In this article, we'll explore how to use Node.js modules, describes how to export and import.
Different module formats
Since the concept of JavaScript did not originally modules, over time there have been various competing format. The following are the mainstream in several formats:
- Asynchronous Module Definition (AMD) format, a browser using the
define
function definition module. - CommonJS (CJS) format, for Node.js, use
require
andmodule.exports
define the dependencies and modules. - ES Module (ESM) format. ES6 (ES2015) begins, JavaScript module supports native format. It uses the
export
public API key export module, and useimport
the import keyword. - System.register format is designed to support the ES5 ES6 module.
- Universal Module Definition (UMD) format, you can use the browser and the Node.js. When the loader module needs to be introduced into the various modules, this is useful.
Note that this article only discuss CommonJS format , it is Node.js in standard format. If you want to learn other formats, I recommend you read this article , the author is SitePoint's Jurgen Van de Moere.
Load Module
Node.js has a series of built-in modules , we do not need to install to use in your code. To this end, we need to use require
the keyword load the module, and assign it to a variable. This module can call any method of exposure.
For example, to list the contents of a directory, you can use the file system module of the readdir
method:
const fs = require('fs');
const folderPath = '/home/jim/Desktop/';
fs.readdir(folderPath, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
Note that, in the CommonJS, the modules are loaded in order of appearance and the synchronization process.
Create and export module
Now let's look at how to create and export module for use elsewhere in the program. Create a user.js
file, and add the following content.
const getName = () => {
return 'Jim';
};
exports.getName = getName;
Then create a directory in the same index.js
file, add the following:
const user = require('./user');
console.log(`User: ${user.getName()}`);
Command node index.js
to run the program, you should see the following output in the console:
User: Jim
What happened here? If you look at user.js
the file, you'll notice that we define a getName
function, then use the exports
keyword so that it can be imported in other places. Then the index.js
file, we introduced this method and execute it. Also note that in the require
statement, plus the module name prefix ./
, because it is a local file. The other is no need to add the file extension.
The method of deriving a plurality of values and
We can export multiple methods and values the same way:
const getName = () => {
return 'Jim';
};
const getLocation = () => {
return 'Munich';
};
const dateOfBirth = '12.01.1982';
exports.getName = getName;
exports.getLocation = getLocation;
exports.dob = dateOfBirth;
index.js
file:
const user = require('./user');
console.log(
`${user.getName()} lives in ${user.getLocation()} and was born on ${user.dob}.`
);
The above code is as follows:
Jim lives in Munich and was born on 12.01.1982.
Note, we derive a dateOfBirth
specified variable name can be anything we want (in this case dob
). It is not necessarily the same as the original variable names.
Various grammatical forms
Also it is mentioned that, at the end you can export in the middle of the methods and values, not necessarily in the file.
E.g:
exports.getName = () => {
return 'Jim';
};
exports.getLocation = () => {
return 'Munich';
};
exports.dob = '12.01.1982';
Also thanks to destructuring assignment , we can selectively import as needed:
const { getName, dob } = require('./user');
console.log(
`${getName()} was born on ${dob}.`
);
As you might expect, this will output log:
Jim was born on 12.01.1982.
Export defaults
In the example above, we derive the function and value. This is very convenient for the auxiliary functions of the entire application needs it, but when you export only a single object module is typically used module.exports
:
class User {
constructor(name, age, email) {
this.name = name;
this.age = age;
this.email = email;
}
getUserStats() {
return `
Name: ${this.name}
Age: ${this.age}
Email: ${this.email}
`;
}
}
module.exports = User;
index.js
file:
const User = require('./user');
const jim = new User('Jim', 37, '[email protected]');
console.log(jim.getUserStats());
The above code output log:
Name: Jim
Age: 37
Email: [email protected]
module.exports
And exports
what is the difference
You may encounter the following syntax on the Internet:
module.exports = {
getName: () => {
return 'Jim';
},
getLocation: () => {
return 'Munich';
},
dob: '12.01.1982',
};
Here we want to export functions and values assigned to module
the exports
properties - of course this is possible:
const { getName, dob } = require('./user');
console.log(
`${getName()} was born on ${dob}.`
);
Output log is as follows:
Jim was born on 12.01.1982.
Well, module.exports
and exports
the difference between what is in the end? The latter is simply an alias you?
Ah, a little, but not quite.
To illustrate what I mean, let's change index.js
the code, the output module
value of:
console.log(module);
The output is:
Module {
id: '.',
exports: {},
parent: null,
filename: '/home/jim/Desktop/index.js',
loaded: false,
children: [],
paths:
[ '/home/jim/Desktop/node_modules',
'/home/jim/node_modules',
'/home/node_modules',
'/node_modules' ] }
We can see, module
there is a exports
property. Let's add something:
// index.js
exports.foo = 'foo';
console.log(module);
This will output:
Module {
id: '.',
exports: { foo: 'foo' },
...
To exports
add properties, also added to module.exports
. This is because exports
is module.exports
a reference.
Which should I use?
Now module.exports
and exports
point to the same object, you use which usually does not matter. E.g:
exports.foo = 'foo';
module.exports.bar = 'bar';
This code will make the export target module becomes { foo: 'foo', bar: 'bar' }
.
However, there is a need to pay attention. You assign module.exports
the contents of the module will be the value of export.
For example as follows:
exports.foo = 'foo';
module.exports = () => { console.log('bar'); };
This will only export an anonymous function. foo
Variable will be ignored.
If you want to learn more, I recommend you read this article .
to sum up
JavaScript module has become an integral part of the ecosystem, it allows us to use smaller components of large programs. I hope this article has done a good introduction for you to use Node.js module, the module as well as help you understand grammar.
Author: James Hibbard
Source: SitePoint
Translation: Translation Station 1024
More front-end technology to make dry in the micro-channel public number: 1024 Verses