学无先后,达者为师

网站首页 前端文档 正文

node.js读取文件成功和失败的时候回调函数err和dataStr的值

作者:wei15552147820 更新时间: 2022-10-11 前端文档

node.js读取文件
在这里插入图片描述js文件代码
const fs = require(‘fs’) //导入文件读取模块
fs.readFile(‘./chengji.txt’,‘utf-8’,function(err,dataStr){
//读取js文件同级目录下面的目录下面的chengji.txt文件
//如果读取文件成功,则err的值为null
//dataStr的值为文件中的值
console.log(err)
console.log(dataStr)
})

cmd运行nodetest.js文件
node nodetest.js

在这里插入图片描述D:\HBuilderProjects\js-test-02>node nodetest.js
null
小红=100 小明=99 张三=88 李四=60

如果读取失败
代码
const fs = require(‘fs’)
fs.readFile(‘./chengji111.txt’,‘utf-8’,function(err,dataStr){
//如果读取文件失败,则err的值为错误对象
// [Error: ENOENT: no such file or directory, open ‘D:\HBuilderProjects\js-test-02\chengji111.txt’] {
// errno: -4058,
// code: ‘ENOENT’,
// syscall: ‘open’,
// path: ‘D:\HBuilderProjects\js-test-02\chengji111.txt’
// }
//dataStr的值为undefined
console.log(err)
console.log(dataStr)
})

在这里插入图片描述D:\HBuilderProjects\js-test-02>node nodetest02.js
[Error: ENOENT: no such file or directory, open ‘D:\HBuilderProjects\js-test-02\chengji111.txt’] {
errno: -4058,
code: ‘ENOENT’,
syscall: ‘open’,
path: ‘D:\HBuilderProjects\js-test-02\chengji111.txt’
}
undefined

原文链接:https://blog.csdn.net/wei15552147820/article/details/127250197

栏目分类
最近更新