Home > Web Front-end > JS Tutorial > body text

How to create a module using Node.js

不言
Release: 2018-12-28 17:07:10
Original
5569 people have browsed it

The node module is a module with convenient functions that can be used by installing it using the npm command in Node.js. It can also be made and used separately, so it can be developed more efficiently. This article will introduce you to the method of creating modules in Node.js. Let’s take a look at the specific content.

How to create a module using Node.js

How to create a module?

Basic knowledge of module creation

Module side (midule. js) source code

exports.方法名 = function (变量) {
  return 进程
};
Copy after login

Description: To create a module in Node.js, you need to use the exports function.

Source code of the calling side (app.js)

var sample  = require('./module.js');
Copy after login
Copy after login
console.log( sample.方法名(参数));
Copy after login

Analysis:

In the first line require('./module.js' );, we call the require module, and we created a module named module.js earlier.

Afterwards, assign it to the variable declared using var sample.

In the second line console.log(sample.methodname(parameter));, the parameter is given the method name of the module assigned to sample, and the result is displayed in console.log.

Let’s create a module in detail

Source code on the module side (module.js)

exports.n= function (num) {
  return num * 3;
};
Copy after login

Instructions: Used in module.js is a method of n, changing the parameter num to 3 times it.

Source code of the calling side (app.js)

var sample  = require('./module.js');
Copy after login
Copy after login
console.log( sample.n(3) );
Copy after login
Analysis:

In app.js, we call module.js in the first line and assign it Give sample.

In the second line of sample.n(3), by giving 3 as argument, the result of 3 times its number is shown in the console.log.

The displayed result is 9.

Summary: This article ends here. For more exciting content, you can pay attention to the relevant tutorial columns of the php Chinese website! ! !

The above is the detailed content of How to create a module using Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template