文件系统 (File System)

杨轶
2023-12-01

文件系统(File System)

基本概念

  • 学习fs模块的API
  • 使用fs模块前,需要引入 cost fs = require(‘fs’);

特点

  • 提供同步异步两种选择
  • 同步导致阻塞
  • 异步操作完成通过回调返回结果

使用

同步写入操作

 let fs = require('fs')
 let fsPath = '7901.txt';
 let fd = fs.openSync(fsPath, 'w');
 //  fd  为文件的id 作为文件的唯一标识

 console.log(fd);
 let str = "shdfhsjfh"
 fs.writeFileSync(fd, str)
 fs.closeSync(fd)

异步写入操作

let fs = require('fs')
let fsPath = "test.txt"
const xxx = "888"
fs.open(fsPath, 'w', (err, fd) => {
    if (!err) {
        fs.writeFile(fd, xxx, (err) => {
            if (!err) {
                console.log("写入成功");
                fs.close(fd, (err) => {
                    if (!err) {
                        console.log("关闭成功");
                    } else {
                        throw err;
                    }
                })
            } else {
                throw err;
            }
        })
    } else {
        throw err;
    }
})

文件流写入操作

// 文件写入
let fs = require('fs')
    // 创建文件流
let wsPath = 'wspath.txt'
let ws = fs.createWriteStream(wsPath)
ws.once('open', () => {
    console.log("通道打开");
    ws.write("11111111");
    ws.write("222222222");
    ws.write("3333333333");
    ws.end();
})
ws.once('close', () => {
    console.log("关闭");
})

文件读取操作

读取图片并写入到另一个文件中(单个文件操作)

let fs = require("fs");

fs.readFile("../images/deskPic1.jpg", (err, data) => {
    if ( !err ) {
        console.log(data);
        //写入图片文件
        fs.writeFile('receiveimage_1.jpg', data, (err, data) => {
            if ( !err ) {
                console.log('transfer success!');
            } else {
                throw err;
            }
        })
    } else {
        throw err;
    }
})

使用文件读入流处理

let fs = require("fs");

let readStream = fs.createReadStream("../images/deskPic2.jpg"); 

let writeStream = fs.createWriteStream("receiveimage_2.jpg");

//监听文件流打开关闭
readStream.once('open', () => {
    console.log('readstream opened');
})

readStream.once('clos', () => {
    console.log('readstream closed');
})

writeStream.once('open', () => {
    console.log('writeStream opened');
})

writeStream.once('clos', () => {
    console.log('writeStream closed');
})

//读入流操作
readStream.on('data', (data) => {
    console.log(data);
    //文件过大时分段读取
    //写入
    writeStream.write(data);
})

简便方法

let fs = require("fs");

let readStream = fs.createReadStream("../images/deskPic2.jpg"); 

let writeStream = fs.createWriteStream("receiveimage_2.jpg");

//创建管道
readStream.pipe(writeStream);
 类似资料: