加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

node.js中的require使用详解

发布时间:2016-11-24 16:54:07 所属栏目:Linux 来源:站长网
导读:代码注释里已经描述的非常的清晰,这里就不多废话了,直接奉上代码: 复制代码 代码如下: /*在node中,可以使用require()函数来加载模块. nbsp;* require函数使用一个参数,参数值可以带有完整路径的模块的文件名,也可以为模块名.当使用node中提供的模块时,

代码注释里已经描述的非常的清晰,这里就不多废话了,直接奉上代码:

复制代码 代码如下:
/*在node中,可以使用require()函数来加载模块.
nbsp;* require函数使用一个参数,参数值可以带有完整路径的模块的文件名,也可以为模块名.当使用node中提供的模块时,在require函数中只需要指定模块名即可.
nbsp;* */
//建立一个页面2.js;代码如下
var name="思思博士";
exports.name=name;
//建立一个页面1.js;代码如下
var two=require("./2.js");
console.log(two.name);
//输出结果:思思博士

/*
nbsp;* 在node中所有的脚本文件都是一个模块文件,因此1.js也是一个模块文件,又由于该文件是在命令行窗口中通过node命令被直接运行的,因此在node中该模块文件被定义为应用程序的主模块
nbsp;* 可以用如下的方法检测出当前的模块是否是主模块
nbsp;* */
if(module===require.main){
nbsp;nbsp;nbsp; console.log("当前模块时主模块");
}
//输出结果:当前模块时主模块

//2.js代码
var name="思思博士";
console.log(name);
exports.name=name;

//1.js代码:
var two=require("./2.js");
var two=require("./2.js");
//虽然引用了2次,但是只是执行了1次console.log(name)的输出.

/*require.resolve(str)
nbsp;* 在node中,可以使用这个函数来查询某个模块文件的带有完整绝对路径的文件名.
nbsp;* */
var url=require.resolve("./2");
console.log(url);
//输出结果:E:nodegys2.js

/*require.cache
nbsp;* 在node中,这个属性代表了所有已被加载模块的缓存区.
nbsp;* */

var two=require("./2.js");
var cache=require.cache;
console.log(cache);
/*输出结果:
nbsp;* { 'E:nodegys1.js':
nbsp;{ id: '.',
nbsp;exports: {},
nbsp;parent: null,
nbsp;filename: 'E:nodegys1.js',
nbsp;loaded: false,
nbsp;children: [ [Object] ],
nbsp;paths:
nbsp;[ 'E:nodegysnode_modules',
nbsp;'E:nodenode_modules',
nbsp;'E:node_modules' ] },
nbsp;'E:nodegys2.js':
nbsp;{ id: 'E:nodegys2.js',
nbsp;exports: { name: '思思博士' },
nbsp;parent:
nbsp;{ id: '.',
nbsp;exports: {},
nbsp;parent: null,
nbsp;filename: 'E:nodegys1.js',
nbsp;loaded: false,
nbsp;children: [Object],
nbsp;paths: [Object] },
nbsp;filename: 'E:nodegys2.js',
nbsp;loaded: true,
nbsp;children: [],
nbsp;paths:
nbsp;[ 'E:nodegysnode_modules',
nbsp;'E:nodenode_modules',
nbsp;'E:node_modules' ] } }
nbsp;* */


//2.js代码
var name="思思博士";
console.log(name);
//1.js代码
//当使用delete关键字删除缓存区中缓存的某个模块对象后,下次加载该模块时将重新运行该模块中的代码.使用代码:

var two=require("./2.js");
var two1=require("./2.js");
console.log("删除前")
delete require.cache[require.resolve("./2.js")];
console.log("删除后");
var two2=require("./2.js");
/*
nbsp;* 输出结果:
nbsp;* 思思博士
nbsp;* 删除前
nbsp;* 删除后
nbsp;* 思思博士
nbsp;* */

小伙伴们是否清楚了node.js中require的使用方法了呢,如有疑问,请留言。

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读