读取文件内容readFile()
readFile(path[, options], callback)
path读取文件的路径options读取文件内容的编码格式(默认十六进制)<Buffer 74 65 73 74>
callback回调函数err错误信息对象- 成功:
null - 失败:错误信息对象
- 成功:
data读取的文件内容- 成功:文件内容
- 失败:
undefined```javascript const fs = require(‘fs’)
fs.readFile(‘./fs/test.txt’, ‘utf8’, (err, data) => { console.log(err) console.log(data) })
```javascriptimport { readFile } from 'fs'readFile('./index.html', 'utf8', (err, data) => {console.log(err)console.log(data)})
判断读取文件是否成功
import { readFile } from "fs";readFile("./index2.html", "utf8", (err, data) => {if (err) {// err.message: 错误信息return console.log("读取文件失败:\n" + err.message);}console.log("读取文件成功:\n" + data);});
错误对象信息
-4058
[Error: ENOENT: no such file or directory, open ‘e:\WWW\yingximu\fs\test.txt’] { errno: -4058, code: ‘ENOENT’, syscall: ‘open’, path: ‘e:\WWW\yingximu\fs\test.txt’ }
[错误:ENOENT:没有这个文件或文件目录,open ‘e:\WWW\yingximu\fs\test.txt’] { 错误编号: -4058, 错误代码:’ENOENT’, 系统调用:’open’, 路径:’e:\WWW\yingximu\fs\test.txt’ }
