1.全局模块定义:无需引用即可随时随地访问。process.env返回项目运行所在的环境变量信息。process.argv参数数组(可以接收通过命令执行node程序时传入的参数),参数1:返回当前节点的路径,参数2:返回当前文件的路径示例(index.js):让num1=parseInt(process.argv[2]);让num2=parseInt(process.argv[3]);console.log(num1+num2);输入命令:nodeindex23输出:52.系统模块定义:需要require()引用,但不需要下载(安装node时已经内置)。path:用于处理文件路径和目录路径的实用程序。letpath=require('path')p='/node/a/1.jpg'path.dirname(p)//路径(/node/a)path.basename(p)//文件名(1.jpg)path.extname(p)//文件扩展名(.jpg)fs:用于文件读写操作。让fs=require('fs')fs.readFile('./a.text',(err,data)=>{if(err){console.log(err)}else{console.log(data.toString())}})//向文件添加内容fs.writeFile('a.txt','test',{flag:'a'},(err)=>{if(err){throwerr}})3.自定义模块定义:需要自己封装模块。1.require1)如果有路径,就去路径中找;constmod1=require('./mod')2)如果没有,去node_modules找;constmod1=require('mod')3)如果没有,去node的安装目录下找。2.exportsandmodule1)valueexports.a=1;exports.b=2;让c=3;使用:mod1.amod1.b2)objectmodule.exports={a:1,b:2}使用:mod1.amod1.b3)functionmodule.exports=function(){}使用:mod1()4)classmodule.exports=class{constructor(name){this.name=name}show(){console.log(this.name)}}使用:letp=newmod1('myname');p.show()四、http模块(重点)模板string`(数字1左边的key),为了识别${}。lethttp=require('http')letfs=require('fs')http.createServer((request,response)=>{//创建http服务fs.readFile(`./${request.url}`,(err,data)=>{//读取文件(path,callback)if(err){response.writeHead(404)//200是默认的,不能写response.end('404notfound')}else{response.end(data)}})}).listen(8088)//创建服务器,必须使用监听端口
