path使用
path.join()
使用path.join()方法,可以把多个路径片段拼接为完整的路径字符串
1 2 3 4 5 6 7 8 | const path=require( 'path' ) // 使用path.join()方法,可以把多个路径片段拼接为完整的路径字符串 //1. ../会抵消前面的路径 const pathStr= path.join( '/a' , '/b/c' , '../' , './d' ) console.log(pathStr) // 2.使用__dirname方法 const pathStr2=path.join(__dirname, './files/1.txt' ) console.log(pathStr2); //输出当前文件所处目录/files/1.txt |
输出效果
path.basename(p[, ext])
方法可以从一个文件路径中获取到文件的名称部分
1 2 3 4 5 6 7 | const path=require( 'path' ) //定义文件的存放路径 const fpath= '/files/index.html' const fullName=path.basename(fpath) //获取完整的文件名 console.log(fullName); //index.html const nameWithoutExt=path.basename(fpath, '.html' ) //移除扩展名 console.log( 'nameWithoutExt' ,nameWithoutExt); |
path.extname(p)
返回路径中文件的后缀名,即路径中最后一个’.’之后的部分。如果一个路径中并不包含’.’或该路径只包含一个’.’ 且这个’.’为路径的第一个字符,则此命令返回空字符串。
1 2 3 4 5 | const path=require( 'path' ) // 使用path.extname()方法可以获取路径中的扩展名部分 const fpath= 'files/index.html' const fext=path.extname(fpath) console.log(fext); |
fs使用
1 2 3 4 5 6 7 8 9 10 | const fs=require( 'fs' ); const path = require( 'path' ); // 读取文件 fs.readFile fs.readFile(path.join(__dirname, '/files/1.txt' ), 'utf-8' , function (err,dataStr) { if (err){ return console.log( '读取错误' ,err) } console.log( '读取成功' ,dataStr); }) console.log(text); |
node.js 中内置模块 path模块的基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | //node加载文件是同步执行的 执行代码会被阻塞 //加载过后的模块会被缓存 ,加载过后的模块module里面的loaded会变为true //node 使用的加载方式是深度优先 // 一 // const path = require('path') // const basePath = '/user/stu'; // const filename = 'hu.text' // const p = path.resolve(basePath,filename) // console.log(p); // 二 // const path = require('path') // const basepath ='./user/stu' // const filename = 'hu.text' // const name = path.resolve(basepath,filename) // const name2 = path.join(basepath,filename) // path.resolve 不只是会对路径/的转化,还会对..或者.进行转化 // path.join 只会对路径中的/进行转化 // console.log(name); // console.log(name2); // 三 // const path = require('path') // const basepath ='./user/stu' // const filename = 'hu.text' // const name = path.resolve(basepath,filename) // console.log(path.dirname(name));//获取路径文件夹 // console.log(path.extname(name));//获取路径的扩展名 // console.log(path.basename(name));//获取文件的名字包括扩展名 |
到此这篇关于node path的使用的文章就介绍到这了,更多相关node path的使用内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!