Nodejs中的require函数的具体使用方法

2020-06-17 06:53:04易采站长站整理

// Importing a module from node_modules or Node.js built-in module:
const crypto = require('crypto');

从以上文档中可以得出以下信息:

require接受一个参数,形参名为id,类型是String。
require函数return的是模块到处的内容,类型是任意。
require函数可以导入模块、JSON文件、本地文件。模块可以通过一个相对路径从node_modules、本地模块、JSON文件中导出,该路径将针对__dirname变量(如果已定义)或者当前工作目录。

require实践

在这里将分类讨论require的实践结论。

require导入JSON

JSON 是一种语法,用来序列化对象、数组、数值、字符串、布尔值和 null 。

在文章的开头就提到了通过require(“./package.json”)文件来读取package.json文件中的version属性。这里将尝试导入info.json文件并查看相关信息。

文件结构目录如下:


.
├── index.js
└── info.json

将info.json文件的内容修改为:


{
"name": "myInfo",
"hasFriend": true,
"salary": null,
"version": "v1.0.0",
"author": {
"nickname": "Hello Kitty",
"age": 20,
"friends": [
{
"nickname": "snowy",
"age": 999
}
] }
}

在info.json当中,包含了字符串、布尔值、null、数字、对象和数组。

将index.js的内容修改如下并在当前terminal运行命令 node index.js ,得到如下结果:


const info = require("./info.json")
console.log(Object.prototype.toString.call(info)) // [object Object]console.log(info.version) // v1.0.0
console.log(info.hasFriend) // true
console.log(info.salary) // null
console.log(info.author.nickname) // Hello Kitty
console.log(info.author.friends) // [ { nickname: 'snowy', age: 999 } ]

可以看到,require导入一个JSON文件的时候,返回了一个对象,Nodejs可以直接访问这个对象里的所有属性,包括String、Boolean、Number、Null、Object、Array。个人猜测这里可能用到了类似于JSON.parse()的方法。

通过这个结论也得出了一种思路,即通过require方法传入JSON文件来读取某些值,如在文章开头中,webpack通过读取package.json文件获取到了version值。

require导入本地js文件

文件结构目录如下:


.
├── index.js
├── module_a.js
└── module_b.js

index.js文件中,分别按顺序导入了module_a和module_b并赋值,然后将这两个变量打印,内容如下:


console.log("*** index.js开始执行 ***")