NodeJs中的fs模块和path模块使用

一、fs读取文件

//1.导入fs模块
const fs  =require('fs');

//2.调用fs.readFile()方法读取文件
//参数:
//参数1:读取文件的存放路径;
//参数2:读取文件时采用的编码
//参数3: 回调函数,拿到读取失败和成功的结果
fs.readFile('./files/1.txt','utf-8',function(err,datastr){
    if(err){
        console.log(err);
    }else{
        console.log(datastr);
    }
})

二、fs写入文件

//1.导入fs模块
const fs  =require('fs');

//2.调用fs.writeFile()方法读取文件
//参数:
//参数1:文件存放的路径;
//参数2:写入的内容
//参数3: 回调函数
var str ='这是调用writeFile写入的一段文字';
fs.writeFile('./files/2.txt',str,function(err,datastr){
    if(err){
        console.log("写入文件失败!");
    }else{
        console.log("写入文件成功!");
    }
})

三、path相关方法

//1.输出当前文件路径地址:E:\Learn\NodeJs\Stage1
console.log(__dirname);
//2.输出文件全部路径,包含文件名:E:\Learn\NodeJs\Stage1\03.path.js
console.log(__filename);

const path = require('path');
const fs = require('fs');

//3.拼接文件路径
const pathStr =path.join('/a','/b/c','../../','./d','e');
console.log(pathStr);//\a\d\e

console.log(path.join(__dirname,'./files/1.txt'));//E:\Learn\NodeJs\Stage1\files\1.txt
console.log(__dirname + '/files/1.txt');//E:\Learn\NodeJs\Stage1/files/1.txt


//4.获取文件名称
const fpath = '/a/b/c/index.html';
const fullname =path.basename(fpath);
console.log(fullname);//index.html

const namewithoutExt =path.basename(fpath,'.html');
console.log(namewithoutExt);//index


//5.获取文件后缀
const fext =path.extname(fpath);
console.log(fext);//.html
posted @ 2022-12-20 17:21  码农阿亮  阅读(179)  评论(0)    收藏  举报