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
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16994718.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。

浙公网安备 33010602011771号