掌握Node.js文件路径操作的秘诀
发表时间: 2019-12-23 11:10
点击右上方红色按钮关注“小郑搞码事”,每天都能学到知识,搞懂一个问题!
大家好!我是/小郑搞码事/的小郑
今天和大家分享Node.js的path模块,它有哪些日常工作中常用的路径操作方式。
以下涉及到的例子都需要引入path模块:
var path = require('path')
// 获取当前文件夹和文件名的完整路径console.log(__dirname)console.log(__filename)// 获取当前执行目录shell所在位置console.log(process.cwd())// 将node命令定位到根目录下process.chdir("/") console.log(process.cwd())// 查询bin目录安装的地方console.log(process.execPath)
var dir = ['foo','bar','baz']// foo/bar/baz - linux console.log(dir.join('/')) // foo\bar\baz - windowconsole.log(dir.join('\'))// /-linux \-windowconsole.log(path.sep) // foo/bar/bazconsole.log(dir.join(path.sep))
// 获取分隔符 :console.log(path.delimiter) process.env.PATH.split(path.delimiter).forEach(function(dir) { console.log(dir)})// 获取环境变量console.log(process.env.PATH)
// path.extnamevar filename = "/foo/bar/baz.txt"var extname = path.extname(filename)console.log(extname)
// 方法:path.basenamevar filename = "/foo/bar/baz.txt"var file = path.basename(filename)console.log(file)
// 方法:path.dirname// /foo/barvar filename = "/foo/bar/baz.txt"var file1 = path.dirname(filename)console.log(file1)
// 方法:path.normalizevar dirName = "/foo/bar/.././bar/../../baz" var normalized = path.normalize(dirName)console.log(normalized) // /bazvar normalizej = path.join("/foo/bar",".././bar","../../","/baz")console.log(normalizej)
// 方法:path.relativevar from = '/foo/bar'var to = '/baz/biff'// 传两个参数都是绝对路径,返回的是第二个参数相对于第一个参数的路径var relative = path.relative(from ,to)console.log(relative) // ../../baz/biff
resolve:返回的是根目录下文件的绝对路径
// path.resolve 返回的是根目录下文件的绝对路径console.log(path.resolve('../foo/bar','./baz'))// /Users/zhengwenping/project/learning/node-learn/n
join:拼路径
var p = path.join('../foo/bar','./baz')// ../foo/bar/bazconsole.log(p)
isAbsolute:判断是否为绝对路径
// falseconsole.log(path.isAbsolute('./foo/bar')) // trueconsole.log(path.isAbsolute('/foo/bar'))
parse:输出路径的信息
/** * { root: '/', dir: '/home/user/dir', base: 'file.txt', ext: '.txt', name: 'file' } */var parsed = path.parse('/home/user/dir/file.txt');console.log(parsed)
format:parse的逆过程
var pf = path.format({ dir: '/home/user/dir', base: 'file.txt'})console.log(pf) // /home/user/dir/file.txt