如何与文件路径互动并在Node中操作它们
系统中的每个文件都有一个路径。
在Linux和macOS上,一个路径可能看起来像。
/users/flavio/file.txt
而Windows电脑则不同,它的结构是这样的。
C:\users\flavio\file.txt
在你的应用程序中使用路径时,你需要注意,因为必须考虑到这种差异。
你可以在你的文件中加入这个模块,使用
const path = require('path')
把这个模块包含在你的文件中,然后你就可以开始使用它的方法了。
从路径中获取信息
给定一个路径,你可以用这些方法提取它的信息。
dirname: 获取文件的父文件夹basename: 获得文件名部分extname: 获得文件的扩展名
例子。
const notes = '/users/flavio/notes.txt'
path.dirname(notes) // /users/flavio
path.basename(notes) // notes.txt
path.extname(notes) // .txt
你可以通过给basename ,指定第二个参数来获得没有扩展名的文件名。
path.basename(notes, path.extname(notes)) //notes
与路径一起工作
你可以通过使用path.join() 来连接一个路径的两个或多个部分。
const name = 'flavio'
path.join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'
你可以使用path.resolve() ,获得相对路径的绝对路径计算。
path.resolve('flavio.txt') //'/Users/flavio/flavio.txt' if run from my home folder
在这种情况下,Node将附加/flavio.txt 到当前工作目录。如果你指定了第二个参数文件夹,resolve 将使用第一个参数作为第二个参数的基础。
path.resolve('tmp', 'flavio.txt')//'/Users/flavio/tmp/flavio.txt' if run from my home folder
如果第一个参数以斜线开头,这意味着它是一个绝对路径。
path.resolve('/etc', 'flavio.txt')//'/etc/flavio.txt'
path.normalize() 是另一个有用的函数,它将尝试并计算实际的路径,当它包含相对的指定符,如 或 ,或双斜杠。. ..
path.normalize('/users/flavio/..//test.txt') ///users/test.txt
resolve和normalize都不会检查路径是否存在。它们只是根据它们得到的信息计算出一个路径。