Nodejs模块化编程思想

nodejs模块化编程

  • nodejs编程遵循就是CMD规范,即一个文件就是一个模块。
  • nodejs的编程语法和js基本一样,并且nodejs支持es6语法。
  • 模块的特点:一个文件就是一个模块,特点,在该模块下,声明的变量,作用域,只作用于当前模块。

代码如下:

let hello1 = "字符串";
let hello2 = 4564;
let hello3 = {
    name: "名称",
    age: 10,
    fn() {
        console.log("执行一个函数!");
    }
};

console.log(hello1);
console.log(hello2);
console.log(hello3);
hello3.fn();

node计算器模块案例

计算器代码如下:

//注意:不需要使用define去定义模块
//一个文件就是一个模块,特点,在该模块下,声明的变量,作用域,只作用于当前模块。
console.log("执行计算器模块代码!");

//公共接口
module.exports = {
    name: "计算器模块",
    add() {
        console.log("加法");
    },
    div() {
        console.log("减法");
    },
    chengf() {
        console.log("乘法");
    },
    chuff() {
        console.log("除法");
    }
};

执行模块代码如下:

let cal = require("./mod/calculator.js");
console.log(cal);
cal.add();

结果:

执行计算器模块代码!
{ name: '计算器模块',
  add: [Function: add],
  div: [Function: div],
  chengf: [Function: chengf],
  chuff: [Function: chuff] }
加法

注意:

  • 对外公开的方式module.exports={};
  • 加载其他模块的方式:require(“路径”),路径写法推荐:"./模块所在的路"

计算圆的周长和面积案例

模块代码如下:

const PI = Math.PI;//圆周率

module.exports = {
    circumference(r) {
        return 2 * PI * r;
    },
    area(r) {
        return PI * r * r;
    }
};

执行模块代码如下:

let cc = require("./mod/calculatorCircle");
console.log("周长:" + cc.circumference(6));
console.log("面积:" + cc.area(6));

Nodejs模块的流程

  • 创建模块 - calculator.js
  • 导出模块 - moudlue.exports | exports.xxx
  • 加载模块 - require(“模块路径”)
  • 使用模块 - calculator.add();

NodeJs继续学习,推荐:http://www.runoob.com/nodejs/nodejs-callback.html

Node的作用

适合用于及时聊天,文件上传等场合;
不是适合,web开发,由于nodejs只是服务器端的脚本语言(基于V8引擎;V8引擎底层是用C++写的);

  • 脚本语言的弱点,自由度高-直接导致的问题,代码可维护性低;
  • 脚本语言,本身没有很多功能框架和解决方案,去应对复杂的业务需求;
  • 一旦代码量多的时候,开发人员或者编写的业务逻辑,就会深陷入无尽的回调函数之中(nodeJs的优点及时他的缺点-回调函数);

成熟的自动化构建工具,fis3,vue-cli,有人维护的!

nodeJs-回调函数

Node.js 异步编程的直接体现就是回调。

异步编程依托于回调来实现,但不能说使用了回调后程序就异步化了。
回调函数在完成任务后就会被调用,Node 使用了大量的回调函数,Node 所有 API 都支持回调函数。

代码如下:

let fs = require("fs");

//阻塞代码
console.log("读取文件...");
let data = fs.readFileSync('input.txt');
console.log(data.toString());

//非阻塞代码
// console.log("读取文件...");
// fs.readFile('input.txt', function (err, data) {
//     if (err) return console.error(err);
//     console.log(data.toString());
// });
// console.log(data.toString());

console.log("程序执行结束!");

猜你喜欢

转载自blog.csdn.net/knowledge_bird/article/details/87888504