nodejs 如何引入其它js文件

本文详细解析了Node.js中使用require()函数加载模块的方法,包括模块的引入、主模块检测、模块缓存及多次引入同一模块时的实际执行情况。通过具体的实例展示了如何在Node.js环境中创建和引入模块,以及如何检测当前模块是否为主模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文通过几个具体实例来分析node.js中使用require()函数来加载模块的方法。

/*在node中,可以使用require()函数来加载模块.

* require函数使用一个参数,参数值可以带有完整路径的模块的文件名,也可以为模块名.当使用node中提供的模块时,在require函数中只需要指定模块名即可.

* */

//建立一个页面hello.js;代码如下

var hello = {

     sayHello:function()

    {

    console.log("number :" + (Math.random()* 100).toFixed(2));

    }

}

module.exports=hello;

//建立一个页面test.js;代码如下

var two=require("./hello.js");

console.log(two.hello());

//输出结果:number:23.65

/*

*在node中所有的脚本文件都是一个模块文件,因此hello.js也是一个模块文件,

*由于该文件是在命令行窗口中通过node命令被直接运行的,因此在node中该模块

*文件被定义为应用程序的主模块

* 可以用如下的方法检测出当前的模块是否是主模块

* */

if(module===require.main){

   console.log("当前模块时主模块");

}

//输出结果:当前模块时主模块

//hello2.js代码

var name="博士 lee";

console.log(name);

exports.name=name;

//test1.js代码:

var two=require("./hello2.js");

var two=require("./hello2.js");

//虽然引用了2次,但是只是执行了1次console.log(name)的输出.

/* require.resolve(str)

* 在node中,可以使用这个函数来查询某个模块文件的带有完整绝对路径的文件名.

 * */

varurl=require.resolve("./hello2");

console.log(url);

//输出结果:E:\node\gys\2.js

/*require.cache

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

* */

var two=require("./hello2.js");

var cache=require.cache;

console.log(cache);

/*输出结果:

 * { 'E:\\node\\gys\\test1.js':

 { id: '.',

 exports: {},

 parent: null,

 filename: 'E:\\node\\gys\\test1.js',

 loaded: false,

 children: [ [Object] ],

 paths:

 ['E:\\node\\gys\\node_modules',

 'E:\\node\\node_modules',

 'E:\\node_modules' ] },

 'E:\\node\\gys\\2.js':

 { id: 'E:\\node\\gys\\hello2.js',

 exports: { name: '思思博士' },

 parent:

 { id: '.',

 exports: {},

 parent: null,

 filename: 'E:\\node\\gys\\test1.js',

 loaded: false,

 children: [Object],

 paths: [Object] },

 filename: 'E:\\node\\gys\\hello2.js',

 loaded: true,

 children: [],

 paths:

 ['E:\\node\\gys\\node_modules',

 'E:\\node\\node_modules',

 'E:\\node_modules' ] } }

 * */

//hello2.js代码

var name="博士 lee";

console.log(name);

//test1.js代码

/*当使用delete关键字删除缓存区中缓存的某个模块对象后,下次加载该模块时将

*新运行该模块中的代码.使用代码:

**/

 

var two=require("./hello2.js");

var two1=require("./hello2.js");

console.log("删除前")

deleterequire.cache[require.resolve("./hello2.js")];

console.log("删除后");

var two2=require("./hello2.js");

/*

 * 输出结果:

 * 博士 lee

 * 删除前

 * 删除后

 * 博士 lee

 * */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值