Node.js学习之路05——fs文件系统之文件的写入和读取

fs文件系统

Node.js中,提供一个 fs模块,以实现文件及目录的读写操作。

1. 同步和异步方法

一般来讲,读取文件使用异步的方法,但是在读取例如系统配置文件时,应该使用同步的方法

2. 普通文件写入和读取

2.1 文件写入

2.1.1 写入一个基本的文本文件

  • 如果不存在要写入的文件,那么将会自动创建一个文件
const fs = require('fs');
let writeData = 'The engaged couple will appear for a photo outside Kensington Palace on Monday afternoon, and will take part in a broadcast interview in the evening.';
fs.writeFile('./writeFile.txt', writeData, 'utf-8', function (err) {
    if (err) {
        console.log('there are some wrong happened~');
    } else {
        console.log('Write successfully~~');
    }
});

2.1.2 复制图片及各种二进制文件(以图片文件为例)

  • 当前文件夹下有一个fileImage.jpg的图片文件
const fs = require('fs');
fs.readFile('./fileImage.jpg', 'base64', function (err, data) {
    if (err) {
        console.log('读取图片失败,请检查错误');
    } else {
        fs.writeFile('./fileImageCopy.jpg', data, 'base64', function (err) {
            if (err) {
                console.log('复制图片文件失败');
            } else {
                console.log('复制图片文件成功');
            }
        });
    }
});

2.2 文件读取

2.2.1 文件异步读取

当前目录下有一个 readFile.txt文件,文件的内容是 hello, this is a read file txt.
const fs = require('fs');
fs.readFile('./readFile.txt', 'utf-8', function(err, data){
    if (err) {
        console.log('read file wrong', err);
    } else {
        console.log('dataAsync');
        console.log(data);
    }
});
/**
 * dataAsync
 * hello, this is a read file txt.
 * **/

2.2.2 文件同步读取

const fs = require('fs');
let dataSync = fs.readFileSync('./readFile.txt', 'utf-8');
console.log('dataSync');
console.log(dataSync);
/**
 * dataSync
 * hello, this is a read file txt.
 * **/

3. 追加数据

3.1 对文本文件同步追加数据

const fs = require('fs');
const appendFileContent = 'this is appendFileContent box';
fs.appendFileSync('./appendFile.txt', appendFileContent, 'utf-8');

3.2 对文本文件异步追加数据

  • appendFile.txt原本内容
hello, this a basic append txt file.

-
const fs = require('fs');
const appendFileContent = 'this is appendFileContent box';
fs.appendFile('./appendFile.txt', appendFileContent, 'utf-8', function (err) {
    if (err) {
        console.log('追加文件操作失败');
    } else {
        fs.readFile('./appendFile.txt', 'utf-8', function (err, data) {
            if (err) {
                console.log('追加成功,但是读取失败');
            } else {
                console.log('追加成功,读取操作成功');
                console.log(data);
            }
        });
    }
});
/**
* 追加成功,读取操作成功
* hello, this a basic append txt file.
* 
* -this is appendFileContent box 
* **/

4. 文件的打开和关闭

fd代表打开文件时返回的文件描述符,在 windows操作系统中,文件描述符也称为文件句柄。

4.1 异步打开文件

const fs = require('fs');
fs.open('./openFile.txt', 'r', (err, fd) => {
    if (err) {
        console.log('open file wrong', err);
    } else {
        console.log('open');
        console.log(fd);
    }
});
/**
* open
* 3
* **/

4.2 同步打开文件

const fs = require('fs');
let openSync = fs.openSync('./openFile.txt', 'r');
console.log('openSync');
console.log(fd);
fs.clodeSync(fd); // 同步关闭文件
/**
* openSync
* 3
* **/

5. fsfs.writefs.read

  • 在使用write方法或者writeSync方法在文件中写入数据时
  • 操作系统的做法是首先将该部分数据读取到内存中,再把数据写到文件中
  • 当数据读取完毕时不代表数据已经写完,因为还有一步部分可能会留在内存缓冲区中.
  • 这时候如果调用close或者closeSync方法关闭文件,那么这部分数据就会丢失,
  • 这时候就可以采用fs模块中的fsync方法对文件进行同步操作,即将内存缓冲区中的剩余数据全部写入文件.

5.1 文件写入

  • 当前目录下有一个write.txt文件,文件的内容是我喜欢编程

5.1.1 异步写入

  • 更加底层的一种写入方法,可以从指定位置写入数据
  • fs.write写入,需要先打开文件,根据文件资源句柄,写入内容
  • fs.write(fd, buffer, offset, length, position, callback(err, written, buffer))
const fs = require('fs');
let buf = new Buffer('我喜欢编程');
fs.open('./write.txt', 'w', function (err, fd) {
    if (err) {
        console.log('open file wrong', err);
    } else {
        fs.write(fd, buf, 3, 9, 0, function (err, written, buffer) {
            if (err) {
                console.log('写文件操作失败');
            } else {
                console.log('写文件操作成功');
                console.log(buffer.toString());
            }
        });
    }
});
/**
 * 写文件操作成功
 * 我喜欢编程
 * **/

5.1.2 同步写入

  • fs.writeSync(fd, buffer, offset, length, position)
const fs = require('fs');
let buf = new Buffer('我喜欢编程');
fs.open('./write.txt', 'w', function (err, fd) {
    if (err) {
        console.log('open file wrong', err);
    } else {
        fs.writeSync(fd, buf, 3, 9, 0);
    }
});

5.2 文件读取

  • 当前目录下有一个open.txt文件,文件的内容是我喜欢编程

5.2.1 同步读取

  • fs.readSync(fd, buffer, offset, length, position, callback)
const fs = require('fs');
 fs.open('./open.txt', 'r', function(err, fd){
    var buf = new Buffer(255).fill(0);
    var bytesRead = fs.readSync(fd, buf, 0, 9, 3);
    console.log(bytesRead);//9
    console.log(buf.slice(0, bytesRead).toString());//喜欢编
});

5.2.2 异步读取

  • fs.read(fd, buffer, offset, length, position, callback(err,bytesRead, buffer))
const fs = require('fs');
fs.open('./open.txt', 'r', function (err, fd) {
    let buf = new Buffer(255).fill(0);//缓存区
    fs.read(fd, buf, 0, 9, 3, function (err, bytesRead, buffer) {
        console.log(buffer.slice(0, bytesRead).toString());//喜欢编
    });
});

fs.open('./open.txt', 'r', function (err, fd) {
    let buf = new Buffer(255).fill(0);//缓存区
    fs.read(fd, buf, 0, 9, 3, function (err, bytesRead, buffer) {
        console.log(buffer.slice(0, bytesRead).toString());//喜欢编
        fs.read(fd, buf, 0, 3, null, function (err, bytesRead, buffer) {
            console.log(buffer.slice(0, bytesRead).toString());//程
        });
    });
});

本文转载于:猿2048Node.js学习之路05——fs文件系统之文件的写入和读取

猜你喜欢

转载自www.cnblogs.com/baimeishaoxia/p/12824467.html