Node.js 如何使用module.exports编写代码

Node.js 如何使用module.exports编写代码

module 是一个离散的程序,在Node.js中的一个文件中。它们与文件绑定,每个文件对应一个模块。 module.exports 是当它在另一个程序或模块中被“ require ”时当前模块返回的对象。

我们将使用一个简单的计算器代码来学习如何在Node.js中使用module.exports。我将一步一步地向您介绍。

步骤1: 在项目文件夹中创建两个文件“app.js”和“calculator.js”。并通过终端初始化项目。

npm init

Node.js 如何使用module.exports编写代码

步骤2: 现在我们有一个基于nodeJS的项目,其入口点为“ app.js ”。现在让我们首先编写“ calculator.js ”的代码。我们将在其中创建一个名为 Calculator 的类。它将有几个成员函数,分别是:

  • preIncrement :用于前缀递增操作
  • postIncrement :用于后缀递增操作
  • preDecrement :用于前缀递减操作
  • postDecrement :用于后缀递减操作
  • add :用于两个数的加法
  • subtract :用于两个数的减法
  • multiply :用于两个数的乘法
  • division :用于两个数的除法

最后,我们通过 module.exports 导出 Calculator 类

calculator.js

// ***** calculator.js file ***** 
class Calculator { 
      
    // Constructor to create object of the class 
    Calculator() { 
          
    } 
  
    // Prefix increment operation 
    preIncrement(a) { 
        return ++a; 
    } 
  
    // Postfix increment operation 
    postIncrement(a) { 
        return a++; 
    } 
  
    // Prefix decrement operation 
    preDecrement(a) { 
        return --a; 
    } 
  
    // Postfix decrement operation 
    postDecrement(a) { 
        return a--; 
    } 
  
    // Addition of two numbers 
    add(a, b) { 
        return a + b; 
    } 
  
    // Subtraction of two numbers 
    subtract(a, b) { 
        return a - b; 
    } 
  
    // Division of two numbers 
    divide(a, b) { 
        return a / b; 
    } 
  
    // Multiplication of two numbers 
    multiply(a, b){ 
        return a * b; 
    } 
} 
  
// Exporting Calculator as attaching 
// it to the module object 
module.exports= Calculator;

步骤3: 现在让我们编写“ app.js ”文件。

首先,我们将通过从“ calculator.js ”文件中要求它来导入 C alculato r类。然后,我们创建一个Calculator类的对象“ calc ”来使用它的成员方法。

app.js

// ***** app.js file  ****** 
// Importing Calculator class 
const Calculator = require('./calculator.js'); 
  
// Creating object of calculator class 
const calc = new Calculator(); 
  
/* Using all the member methods  
defined in Calculator */
  
console.log(calc.preIncrement(5)) 
  
console.log(calc.postIncrement(5)) 
  
console.log(calc.preDecrement(6)) 
  
console.log(calc.postDecrement(6)) 
  
console.log(calc.add(5, 6)) 
  
console.log(calc.subtract(5, 6)) 
  
console.log(calc.divide(5, 6)) 
  
console.log(calc.multiply(5, 6))

运行应用程序的步骤: 打开终端并输入以下命令。

node app.js

Node.js 如何使用module.exports编写代码

通过这种方式,您可以在Node.js中使用module.exports。在这里,您可以传递任何变量、字面值、函数或对象来替代class。稍后可以使用require()来导入它。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程