Home  >  Article  >  Web Front-end  >  How to create a module using Node.js

How to create a module using Node.js

不言
不言Original
2018-12-28 16:54:055523browse

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 进程
};

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');
console.log( sample.方法名(参数));

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;
};

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');
console.log( sample.n(3) );

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!

Statement:
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