环境&&工具
node.js
- CommonJS
- 每个文件是一个模块,有自己的作用域
- 每个模块内部module变量代表模块本身
- module.exports属性代表模块对外的接口 //区分exports与module.exports的区别
- global
- process
require特性
- module被加载的时候执行,加载后缓存
- 一旦出现某个模块被循环加载,就只输出已执行部分,未执行部分不会输出
- /绝对路径 , ./相对路径。 支持js、json、node扩展名,
export
const exports=module.exports //类似快捷方式。 注意:不要修改指向exports.test = 100;复制代码
global //global.testVar2 = 200
process
const { argv, //所有参数 argv0, //argv的引用,少用 execArgv, //调用nodejs命令时,传入的参数。 execPath //执行脚本路径 } = process;const {env} = process; //环境process.cwd() //当前路径setimmediate() //异步,等同步执行完了调用,下一个队列process.nextTick() //队列尾部,比上一个执行的早 > settimeout > setimmediate复制代码
***:event loop原理相关
process.nextTick> setTimeout > setImmediate
path
const {normalize} = require('path')normalize('/usr//local/bin')normalize('/usr//local/../bin')const {join} = require('path');join('/usr', '/local','/bin/');join('/usr','../local/','bin/');const {resolve} = require('path')const {basename,dirname,extname} = require('path')const path = require('path')__dirname __filename //绝对路径process.cwd() //当前路径path.resolve('./)复制代码
Buffer
- 处理二进制文件流
- 实例类似整数数字 ,大小固定
- C++代码在V8堆外 分配物理内存
- buf.length
- buf.toString()
- buf.fill() 填充数据
- buf.equals()
- buf.indexOf()
- buf.copy()
Buffer.byteLength('test') Buffer.isBuffer(Buffer.from([1,2,3]))const buf1 = Buffer.from('this') const buf2 = Buffer.from('is')const buf = Buffer.concat([buf1,buf2])const buf = Buffer.from('this is a test!')buf.lengthconst buf1 = Buffer.alloc(10); //申请的空间大小 ,默认填充const buf2 = Buffer.allocUnsafe(10); //申请的空间大小buf2[0]=2;console.log(buf.toString('base64'));const buf3 = Buffer.alloc(10);console.log(buf3);console.log(buf3.fill(10,2,3)); //填充数据10,从第2个开始,到第6个const buf4 = Buffer.from('this')const buf5 = Buffer.from('this')buf4.equals(buf5)buf4.indexOf('t')cosnt StringDecoder = require('string_decoder').StringDecoder;const decoder = new StringDecoder('utf8');const buf = Buffer.form('test copy');for(let i=0;i
事件
const EventEmitter = require('events');class CustomEvent extends EventEmitter{ //step1:继承事件}const ce = new CustomEvent(); //step2:实例化ce.on('test', ()=>{ //step3:绑定事件 console.log('this is a test!');})ce.on('error', (err,time)=>{ //step3:绑定事件.带参 console.log('err');}) ce.once('onceTest',()=>{ })setInterval(()=>{ ce.emit('test'); ce.emit('error',new Error('oops!'),Date.now()); ce.emit('onceTest')},500);--------------------------------------------------------ce.on('test',fn1) ce.on('test',fn2) setTimeout(()=>{ ce.removeListener('test',fn2) //ce.removeAllListener('test')},1500)复制代码
fs文件系统
const fs=require('fs');fs.readFile('./32_readfile.js','utf8',(err,data)=>{ //读 if(err) throw err; console.log(data);})const data= fs.readFileSync('./01_run.js','utf-8');const fs=require('fs')fs.writeFile('./test','this is a test',{ //写 encoding:'utf5'},err=>{ if(err) throw err; console.log('done!')}) const fs = require('fs')fs.stat('./34_stat.js',(err,stats)=>{ //文件状态 if(err) throe err; console.log(stats.isFile()) console.log(stats.isDirectory())})fs.rename('./test','test1.txt',err=>{ //重命名...})fs.unlink('./test'err=>{ //删除 })fs.readdir('./',(err,files)=>{ //读取文件 })fs.mkdir('test',err=>{ //创建文件夹})fs.rmdir('test',err=>{ //删除})fs.watch('./',{ //监听文件变化 recursive:true},(eventType,filename)=>{ console.log(eventType,filename);})复制代码
数据流
const fs=require('fs');const rs = fs.createReadStream('./41_readstream.js');rs.pipe(process.stdout); //把当前文件读出来const ws = fs.createWriteStream('./test.txt'); //写入流const setInt = setInterval(()=>{ const num = parseInt(Math.random() * 10); if(num <7){ ws.write(num + '') }else{ clearInterval(setInt); ws.end() }},200)ws.on('finish',()=>{ console.log('done!')})复制代码
处理回调地狱 callback hell
const fs = require('fs');const promisify = require('util').promisify;const read = promisify(fs.readFile) //处理回调read('./test.js').then(data=>{ console.log(data.toString());})catch(ex =>{ console.log(ex)})--------------------async function test(){ try{ const content = await read('./test.js'); //异步语法糖模式 }cacth(e){ ... } console.log(content)}复制代码
复制代码