path使用

path.join()

使用path.join()方法,可以把多个路径片段拼接为完整的路径字符串

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

输出效果

node path的使用详解

path.basename(p[, ext])

方法可以从一个文件路径中获取到文件的名称部分

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);

node path的使用详解

path.extname(p)

返回路径中文件的后缀名,即路径中最后一个'.'之后的部分。如果一个路径中并不包含'.'或该路径只包含一个'.' 且这个'.'为路径的第一个字符,则此命令返回空字符串。

const path=require('path')
// 使用path.extname()方法可以获取路径中的扩展名部分
const fpath='files/index.html'
const fext=path.extname(fpath)
console.log(fext);

node path的使用详解

fs使用

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 path的使用详解

node.js 中内置模块 path模块的基本使用

//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));//获取文件的名字包括扩展名
原文地址:https://blog.csdn.net/qq_40190624/article/details/127684510

相关文章: