Node.js-fs文件系统模块
fs模块是Node.js官方提供的、用来操作文件的模块。它提供了一系列的方法和属性,用来满足用户对文件的操作需求。
如果要在JavaScript代码中,使用fs模块来操作文件,则需要使用如下的方式先导入它:
fs.readFile使用方法:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 
 | const fs = require("fs");
 
 fs.readFile("./11/1.txt", "utf-8", function (err, data) {
 
 
 
 if (err) {
 
 console.log(err);
 } else {
 
 console.log(data);
 }
 
 
 });
 
 | 
判断文件读取是否成功:可以判断err对象是否为null,从而知晓文件读取的结果:
| 12
 3
 4
 5
 6
 7
 8
 
 | const fs = require("fs");fs.readFile("./11 /1.txt", "utf-8", function (err, data) {
 if (err) {
 console.log("读取文件失败"+err);
 } else {
 console.log("读取文件成功"+data);
 }
 });
 
 | 
fs.writeFile()使用:
格式:
| 12
 3
 4
 5
 
 | fs.writeFile(file,data[,options],callback)
 
 
 
 
 | 
fs.writeFile()实例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | const fs = require("fs");
 fs.writeFile("./11/2.txt", "hello world", function (err) {
 
 
 
 
 
 
 if (err) {
 console.log("写入文件失败" + err);
 } else {
 console.log("写入文件成功");
 }
 });
 
 | 
readFile和writeFile联合使用实例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 
 | 
 
 
 
 
 const fs = require("fs");
 
 fs.readFile("./11/3.txt", "utf-8", function (err, data) {
 if (err) {
 console.log("读取文件失败" + err);
 } else {
 console.log("读取文件成功" + data);
 
 const arr = data.split(" ");
 
 const arrNew = [];
 arr.forEach(item => {
 
 arrNew.push(item.replace("=", ":"));
 });
 console.log(arr);
 
 const str = arrNew.join('\r\n');
 console.log(str);
 
 fs.writeFile("./11/4.txt", str, function (err) {
 if (err) {
 console.log("写入文件失败" + err);
 } else {
 console.log("写入文件成功");
 }
 });
 }
 });
 
 | 
路径动态拼接问题:
在使用fs模块操作文件时,如果提供的操作路径是以./或../开头的相对路径时,很容易出现路径的动态拼接错误的问题。
原因:代码在运行的时候,会执行node命令时所处的目录,动态拼接出被操作文件的完整路径。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | const fs = require("fs");
 
 
 
 
 console.log(__dirname);
 fs.readFile(__dirname+"/11/1.txt", "utf-8", function (err, data) {
 if (err) {
 console.log("读取文件失败" + err);
 } else {
 console.log("读取文件成功" + data);
 }
 });
 
 | 
path模块是Node.js官方提供的一个内置模块,用于处理文件路径。它提供了一些常用的文件路径处理方法用来解决路径拼接的问题。
例如,我们可以通过path.join()方法来拼接路径。
path.basename()方法返回一个路径的最后一部分,即文件名。
如果要在JavaScript代码中,使用path模块来处理路径,那么,我们需要在代码中,引入path模块。
const path = require(“path”);
路径拼接
path.join()方法,可以接受多个参数,并且每个参数都是一个字符串。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | const pathstr = path.join('/a', '/b/c','../','./d','e');
 console.log(pathstr);
 
 
 
 
 const fpath = '/a/b/c/d/e.txt';
 console.log(path.basename(fpath));
 console.log(path.basename(fpath, '.txt'));
 
 |