ES6读取文件

** 需求:已知一个路径,读取文件内容并返回 **

  • 普通读取文件方式:
1
2
3
4
5
6
const fs = require("fs")
const path = require("path")
fs.readFile(path.join(__dirname, "./1.txt"), "utf-8", (err, dataStr) => {
if (err) throw err
console.log(dataStr)
})
  • 封装函数:
    1
    2
    3
    4
    5
    6
    7
    8
    function getFileByPath(fpath, callback) {
    fs.readFile(fpath, "utf-8", (err, dataStr) => {
    // 如果报错,后面的代码无意义
    if (err) return callback(err)
    // console.log(dataStr)
    callback(null, dataStr)
    })
    }
  • 调用函数:
    1
    2
    3
    4
    getFileByPath(path.join(__dirname, "./1.txt"), (err, dataStr) => {
    if (err) return console.log(err.message)
    console.log(dataStr)
    })

** 新需求:顺序读取文件 **

  • 回调嵌套:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    getFileByPath(path.join(__dirname, "./1.txt"), (data) => {
    console.log(data)
    getFileByPath(path.join(__dirname, "./2.txt"), (data) => {
    console.log(data)
    getFileByPath(path.join(__dirname, "./3.txt"), (data) => {
    console.log(data)
    })
    })
    })
  • 用 Promise 改造:

    1
    2
    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
    36
    37
    38
    39
    function getFileByPath(fpath) {
    // 改造 function
    return new Promise(function (resolve, reject) {
    fs.readFile(fpath, "utf-8", (err, data) => {
    if (err) reject(err)
    resolve(data)
    })
    })
    }
    getFileByPath("./1.txt")
    .then(
    function (data) {
    // 读取文件
    console.log(data)
    return getFileByPath("./2.txt")
    },
    function (err) {
    console.log(err.message)
    return getFileByPath("./2.txt")
    }
    )
    .then(
    function (data) {
    console.log(data)
    return getFileByPath("./3.txt")
    },
    function (err) {
    console.log(err.message)
    return getFileByPath("./3.txt")
    }
    )
    .then(
    function (data) {
    console.log(data)
    },
    function (err) {
    console.log(err.message)
    }
    )