Node的文件系统

本文详细介绍了Node.js的文件系统操作,包括同步和异步读写文件、回调函数的使用、fs模块的主要函数,如readFile、writeFile、readFileSync等,以及文件的打开、关闭、目录操作等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

Node的文件系统

1、同步和异步

2、什么是回调(回调函数)

3、fs模块的常用函数


Node的文件系统

FS(FileSystem):实现对文件的IO操作。fs是Node的的模块,需要导入

var fs = require("fs")

1、同步和异步

(1)同步:程序在涉及到文件IO时,必须等到文件IO操作结束后再执行后续的操作

(2)异步:程序在涉及到文件IO时,不等待文件IO操作结束,继续执行后续的操作,当文件IO操作结束后系统uui通知程序处理文件

2、什么是回调(回调函数)

“回调”即“回头调用”,“回调函数”是指函数定义后并不立即调用,而是等到某个事件被触发时再调用。具有异步性

3、fs模块的常用函数

(1)读文件:

(1)readFile():用于异步读取数据。  - - - - 非阻塞方式读

readFile(filename,function(err,buffer){ //异步读取文件

                处理文件的代码

        })

 readFile方法的第一个参数是文件的路径,可以是绝对路径,也可以是相对路径。注意,如果是相对路径,是相对于当前进程所在的路径(process.cwd()),而不是相对于当前脚本所在的路径。

 "function(err,buffer)" :回调函数,'err'存放的是读文件失败的信息;'buffer'存放文件的内容

(2)readFileSync():用于同步读取文件,返回一个字符串。- - - -阻塞方式

var text = fs.readFileSync(fileName, 'utf8');

readFileSync方法的第一个参数是文件路径,第二个参数可以是一个表示配置的对象,也可以是一个表示文本文件编码的字符串。默认的配置对象是{ encoding: null, flag: 'r' },即文件编码默认为null,读取模式默认为r(只读)。如果第二个参数不指定编码(encoding),readFileSync方法返回一个Buffer实例,否则返回的是一个字符串。

 示例:创建一个名为input.txt的文件(内容自定)

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

//2、异步读取
fs.readFile('input.txt',function (err,buf){
    if(err){
        return console.error(err)
    }
    console.log("异步读取文件:",buf.toString())
})
console.log('2011-1-2')

 

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

var data = fs.readFileSync('input.txt','utf8');
console.log("同步读:" + data.toString());
console.log("2011-1-2");

这两个例子说明非阻塞阻塞调用的概念。

第一个例子(异步读-非阻塞)程序不等待文件读取,它只是进行打印“Program Ended”,同时程序无阻塞继续读取文件

第二个例子(同步读-阻塞)直到它读取该文件,然后前进到结束程序的地方。

(2)打开文件

 fs.open(path, flags[, mode], callback)

path - 文件名,包括路径字符串

flags - 标志要打开的文件的方式。

mode - 设置文件模式,但前提是已创建该文件。它默认为0666,读取和写入。

callback - 这是回调函数,有两个参数(err, fd)。

flags参数的取值:

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

fs.open('input.txt','r+',function (err,fd){
    if(err){
        return console.error(err)
    }
    console.log('fd',fd);
    console.log('打开文件成功!')
})

 (3)获取文件信息:它产生一个对象,该对象包含了该文件或目录的具体信息。通过该方法,判断正在处理的是一个文件,还是一个目录。

fs.stat(path, callback)

path - 文件名,包括路径字符串。

callback - 回调函数得到两个参数(err, stats) 。

stat(path,function(err,states){
			
	'err':打开文件异常时的信息
				
	'states':文件的状态信息
})
//1、导入fs模块
const fs = require('fs')

fs.stat('input.txt',function (err,stats){
    if(err){
       return console.error(err)
    }
    console.log("文件状态:",stats)

    //检查
    console.log("isFile? ----",stats.isFile())//判断对象是否是文件
    console.log("isDirectory? ----",stats.isDirectory())//判断对象是否是目录
})

 

 (4)写入文件

(1)writeFile  --- 异步写入文件

fs.writeFile(filename, data[, options], callback)

如果文件已经存在将会覆盖文件

filename - 文件名,包括路径字符串

data - 字符串或缓冲区将被写入到文件中

options - 一个对象,用于指定编码格式。默认编码是UTF8。

callback - 回调函数获取一个参数err,用于在发生任何写入错误时返回错误。

const fs = require('fs')

//1、向input.txt中写入内容
fs.writeFile('input.txt','西安钟楼',function (err){
    if(err){
        return  console.error(err)
    }
    console.log('写入文件成功!')
})

 

  (2)writeFileSync:同步写入文件

fs.writeFileSync(fileName, str, 'utf8');

(5)读取文件(以二进制方式读)

 fs.read(fd, buffer, offset, length, position, callback)

fd - 通过文件fs.open()方法返回的文件描述符

buffer - 被写入数据的缓冲区

offset - 偏移量,开始写入缓冲区的位置

length - 整数,指定要读取的字节数

position - 整数,指定从文件中开始读取。如果位置为null,数据将从当前文件位置读取。

callback - 回调函数获取三个参数,(err, bytesRead, buffer).

 (6)关闭文件

fs.close(fd, callback)

fd - 这是通过文件fs.open()方法返回的文件描述符。

callback - 这是回调函数

const fs = require('fs')

//读取二进制文件
var buf = new Buffer(1024)
fs.open('input.txt','r+',function (err,fd){
    if(err){
        return console.error(err)
    }
    console.log("打开文件成功!")
    fs.read(fd,buf,0,buf.length,0,function (err,bytes){
        if(err){
            return console.error(err)
        }
        if(bytes > 0){
            let str = buf.slice(0,bytes).toString();
            console.log("读取的内容是:",str)
        }
    })
    fs.close(fd,function (err){
        if(err){
            return console.error(err)
        }
        console.log('文件关闭成功!')
    })
})

 (7)创建目录

fs.mkdir(path[, mode], callback)

path - 包括路径的目录名。

mode - 要设置的目录权限。

callback - 回调函数

const  fs = require('fs')

fs.mkdir('./deyun',function (err){
    if(err){
        return console.error(err)
    }
    console.log('创建目录成功!')
})

 

 (8)读取目录

fs.readdir(path, callback)

fs.readdir('./deyun',function (err,files) {
    if (err){
        return console.error(err)
    }
    files.forEach(function (file) {
        console.log(file)
    })
})

 (9)删除目录

fs.rmdir(path, callback)

(10)文件复制

fs.copyFile(源文件,目标文件,回调函数)

fs.copyFile('./input.txt','./target.txt',function (err) {
    if (err){
        return console.error(err)
    }
    console.log('文件拷贝成功!')
})

(11)给文件中追加内容:将内容添加到文件的末尾,若给定的文件不存在则创建文件,创建的新文件名就是给定的文件名

fs.appendFile(filename,content,callback)

let content = "\n野火烧不尽,\n春风吹又生";
fs.appendFile('./input.txt',content,function (err){
    if (err){
        return console.error(err)
    }
    console.log('追加内容成功!');
})

(12)删除文件

fs.unlink(path, callback)

fs.unlink('./target.txt',function (err) {
    if (err){
        return console.error(err)
    }
    console.log('删除文件成功!')
})

(13)重命名

fs.rename(oldPath, newPath, callback)

oldPath <String> | <Buffer>

newPath <String> | <Buffer>

callback <Function> 回调只有一个可能的异常参数

fs.rename('./input.txt','./test.txt',function (err){
    if (err){
        return console.error(err)
    }
    console.log('重命名成功!')
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陛下,再来一杯娃哈哈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值