NodeJs基础学习--模块(3)

2019-02-27  本文已影响0人  WanggW

在node环境中,可以直接使用 node hello.js 运行一个js文件,在程序开发中,代码会越来越长,越写越多,维护时则难度越来越大;

为了编写的可维护性,我们可以根据功能将很多函数进行分组,拆分为多个js文件,这样的多个js文件称为模块

'use strict';
 
var s = 'Hello';
function greet(name) { 
  console.log(s + ', ' + name + '!');
}
 
module.exports = greet;

以上hello.js文件,将greet这个函数对外导出,使其他引用hello.js文件的其他模块,可以使用greet函数;

例如

'use strict';
// 引入hello模块:
var greet = require('./hello');
var s = 'Michael';
greet(s); // Hello, Michael!
//注意到引入hello模块用Node提供的require函数
var greet = require('./hello');

在repuire引用时,应注意路径;
如果只写了模块名,node会依次在内置模块、全局模块和当前模块查找;

在引用时如果报错:

module.exports = abc;//对外暴露变量
//在其他模块中引用变量
var def = require('模块名');

输出的变量可为:任意对象、函数、数组等,引入之后具体为什么,取决于被引入的模块输出了什么。

上一篇下一篇

猜你喜欢

热点阅读