当前位置: 首页 > 后端技术 > Node.js

Node.js基本使用(Path,Buffer,fs)

时间:2023-04-03 13:05:06 Node.js

Pathconstpath=require('path')console.log(__filename)//获取路径的基本名称,最后一部分/***返回一个在接收路径的最后部分*第二个参数表示扩展名,如果不设置则返回带后缀的完整文件名*当第二个参数作为后缀时,如果在当前路径中没有匹配到忽略*处理目录路径时如果末尾有路径分隔符,也会被忽略*/console.log(path.basename(__filename))console.log(path.basename(__filename,'.js'))//第二个可选参数,匹配后缀,如果有则显示文件名,如果没有则完整文件名console.log(path.basename(__filename,'.css'))console.log(path.basename('/a/b/c'))//返回路径的最后一部分//获取路径目录名(path)/***返回最后一部分的上层目录的路径path*/console.log(path.dirname(__filename))console.log(path.dirname('/a/b/c'))///a/bconsole.log(path.dirname('/a/b/c/'))///a/b//getpathExtension/***返回路径path中对应文件的后缀*如果路径path中有多个点,则匹配来自的内容last指向结尾**/console.log(path.extname(__filename))//.jsconsole.log(path.extname('/a/b'))//空console.log(path.extname('/a/b/index.html.js.css'))//.cssconsole.log(path.extname('/a/b/index.html.js.'))//.//解析路径/***接收路径并返回包含不同信息的对象*rootdirbaseextname(名称的最后一部分)*/constobj=path.parse('a/b/c/index.html')//{//root:'',//dir:'a/b/c',//base:'index.html',//ext:'.html',//name:'index'//}constobj1=path.parse('a/b/c/')//{root:'',dir:'a/b',base:'c',ext:'',name:'c'}constobj2=path.parse('a/b/c')//{root:'',dir:'a/b',base:'c',ext:'',name:'c'}constobj3=path.parse('./a/b/c')//{root:'',dir:'./a/b',base:'c',ext:'',name:'c'}//序列化路径constobj4=path.parse('./a/b/c')console.log(path.format(obj4))//./a/b\c//判断当前路径是否为绝对路径console.log(path.isAbsolute('foo'))//falseconsole.log(path.isAbsolute('/foo'))//trueconsole.log(path.isAbsolute('///foo'))//trueconsole.log(path.isAbsolute(''))//falseconsole.log(path.isAbsolute('.'))//falseconsole.log(path.isAbsolute('../bar'))//false//加入路径console.log(path.join('a/b','c','index.html'))//a\b\c\index.htmlconsole.log(path.join('/a/b','c','index.html'))//\a\b\c\index.htmlconsole.log(path.join('a/b'、'c'、'../','index.html'))//a\b\index.htmlconsole.log(path.join('a/b','c','./','index.html'))//a\b\c\index.htmlconsole.log(path.join('a/b','c','','index.html'))//a\b\c\index.htmlconsole.日志(路径。加入(''))//。当前工作目录//标准化路径console.log(path.normalize('a/b/c/d'))//a\b\c\dconsole.log(path.normalize('a///b/c../d'))//a\b\c..\dconsole.log(path.normalize('a//\\b/c\\/d'))//a\b\c\dconsole.log(path.normalize('a//\b/c\\/d'))//a\c\d反斜杠后面的字母有特殊含义console.log(path.normalize(''))//.//绝对路径console.log(path.resolve())//打印当前目录console.log(path.resolve('index.html'))//打印当前目录/index.html最常见写法console.log(path.resolve('a','b'))//当前目录\a\b/***resolve([from],to)putto部分拼接为绝对路径.如果拼接后不是绝对路径,*则添加当前工作目录,使其成为绝对路径from*/console.log(path.resolve('/a','b'))//D:\a\b其中'/a''b'变为toconsole.log(path.resolve('a','/b'))//D:\b此处a被忽略,'/b'变为toconsole.log(path.resolve('/a','/b'))//D:\b此处'/a'被忽略'/b'变为toBufferBuffer使得Js可以操作二进制全局变量而不需要全局变量实现nodejs平台下的二进制数据操作,不占用V8堆内存的内存空间内存的使用是受控的通过Node,v8的GC回收一般是和Stream流一起使用,作为数据缓冲区alloc创建一个指定字节大小的bufferallocUnsafe创建一个指定大小(unsafe)的buffer从接收数据,创建一个bufferconstb1=缓冲区.alloc(10);//单位为字节console.log(b1);//<缓冲区00000000000000000000>constb2=Buffer.allocUnsafe(10);控制台日志(b2);//<缓冲区00000000000000000000>constb3=Buffer.from("中");console.log(b3);//十六进制utf-8,一个汉字,三个字节constb4=Buffer.from([1,2,3]);console.log(b4);//constb5=Buffer.from([1,2,"medium"]);console.log(b5);//constb6=Buffer.from([0xe4,0xb8,0xad]);console.log(b6,b6.toString());//<缓冲区e4b8广告>;consta1=Buffer.alloc(3);consta2=Buffer.from(a1);//空间不共享console.log(a1,a2);//<缓冲区000000><缓冲区000000>a1[0]=1;console.log(a1,a2);//fill使用数据填充bufferwrite将数据写入buffertoString从buffer中提取数据切片拦截bufferindexOf查找buffer中的数据copy复制buffer中的数据letbuf=Buffer.alloc(6);buf.fill("123",1,3);//第二个参数是填充开始下标位置,第三个代表结束位置,这个位置是获取不到的console.log(buf,buf.toString());//123123,如果长度不够就填充,如果超过就拦截buf.fill(123)console。日志(buf,buf.toString());//{{{{{{7b特殊的uft-8编码是{buf.write("123",1,4);//第二个参数为起始位置,第三个参数为长度console.log(buf,buf.toString());//<缓冲区313233000000>123buf=Buffer.from("默认值");console.log(buf,buf.toString());//<缓冲区e9bb98e8aea4e580bc>默认值console.log(buf,buf.toString("utf-8",3,9));//<缓冲区e9bb98e8aea4e580bc&g吨;默认值,第二个参数表示开始下标,第三个表示结束位置buf=Buffer.from("defaultvalue");letb1=buf.slice();//第一和第二个参数表示开始位置和结束位置,不分头尾,如果是负数,表示从末尾开始,-3会打印出“值”console.log(b1,b1.toString());//默认值---从头到尾截取buf=Buffer.from("defaultvalue,Asilov");console.log(buf,buf.indexOf("A"));//10----中文占三个字节,所以A的下标为10console.log(buf,buf.indexOf("啊",4));//-1letb1=Buffer.alloc(6);letb2=Buffer.from("前端");b2.copy(b1);//将b2复制到b1console.log(b1.toString(),b2.toString());//前端letb1=Buffer.alloc(6);letb2=Buffer.from("frontend");b2.copy(b1);//将b2复制到b1,第二个参数表示复制的起始位置,第三个参数从sourcebuffer中读取起始位置,第四个参数表示sourcebuffer读取的结束位置,不分首尾结束console.log(b1.toString(),b2.toString());//前端letb1=Buffer.from("frontend");让b2=Buffer.from("performance");letb=Buffer.concat([b1,b2]);console.log(b,b.toString());//前端性能letb3=Buffer.concat([b1,b2],9);console.log(b3,b3.toString());//前端letb4=Buffer.alloc(3);console.log(Buffer.isBuffer(b4));//true在Buffer上实现了数组的拆分操作//buffer创建后长度固定,实现了一个拆分方法ArrayBuffer。prototype.split=function(sep){letlen=Buffer.from(sep).length;letresult=[];letstart=0;letoffset=0;while((offset=this.indexOf(sep,start)!==-1)){result.push(this.slice(start,offset));start=offset+len;//更新起始位置}result.push(this.slice(start))returnresult;};letbuf="小明喜欢吃馒头,吃水果,吃米饭";letbufArr=buf.split("eat");console.log(bufArr);//['小明喜欢','蒸buns,','fruits,','rice','']buffer应用场景图片base64编码转换constfs=require('fs');constpath=require('path');//函数对文件数据进行编码到base64编码的字符串函数base64_encode(文件){让位图=fs.readFileSync(文件);returnBuffer.from(bitmap).toString('base64');}//从base64编码字符串创建文件的函数functionbase64_decode(base64str,file){fs.writeFileSync(file,bitmap);}letbase64str=base64_encode(path.join(__dirname,'./a.png'));控制台日志(base64str);base64_decode(base64str,path.join(__dirname,'copyA.png'));文件读取缓冲区乱码问题的解决方法1//可读流有设置编码的方法setEncoding():默认不设置字符编码,流数据返回一个Buffer对象如果设置了字符编码,则流数据返回指定编码的字符串//fs.createReadStream的options中默认highWaterMark为64kconstrs=fs.createReadStream(path.join(__dirname,'1.txt'),letrs=fs.createReadStream('test.md',{highWaterMark:11});rs.setEncoding('utf8');方案2constres=fs.createReadStream(path.join(__dirname,'1.txt');//将SmallBuffers拼接成大Buffer对象letchunks=[];letsize=0;res.on('data',function(chunk){chunks.push(chunk);size+=chunk.length;});res.on('end',function(){letbuf=Buffer.concat(chunks,size);letstr=iconv.decode(buf,'utf8');//累积缓冲区,iconv控制台.log(str);});FSFs基本操作类FscommonAPIcommonflagoperatorrreadablewwritablessynchronous+执行相反操作xexclusiveoperationaappend操作代码示例constfs=require("fs");//readFilefs.readFile(path.resolve("file.txt"),"utf-8",(err,data)=>{console.log(err);//null,如果路径错误,会打印错误信息console.log(data);//123});fs.writeFile("data.txt","hellonode.js",(err)=>{if(!err){fs.readFile("data.txt","utf-8",(err,data)=>{console.log(data);//你好node.js});}});fs.writeFile("data.txt","hellonode.js",(err)=>{//writeFile覆盖写入操作if(!err){fs.readFile("data.txt","utf-8",(err,data)=>{console.log(data);//hellonode.js});}});fs.writeFile("data.txt","abcd",{模式:438,flag:'r+',//该模式默认不会清除文件编码:'utf-8'},(err)=>{//writeFile覆盖写入操作if(!err){fs.readFile("data.txt","utf-8",(err,data)=>{console.log(data);//abcdonode.js});}});//追加写入fs.appendFile('data.txt','frontend',(err)=>{console.log("write")})fs.copyFile('data.txt','dataCopy.txt',(err)=>{console.log("copysuccess")})fs.watchFile('data.txt',{interval:20},(cur,pre)=>{//每20毫秒监控一次if(cur.mtime!==pre.mtime){console.log("filemodify")//修改后打印fs.unwatchFile('data.txt')//取消监视}})