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
判断文件是否读取成功代码
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)
if(err){
console.log(‘failed’)
//判断err可以转为true,则文件读取失败
}
//否则文件读取成功
console.log(‘success’)
})
D:\HBuilderProjects\js-test-02>node nodetest.js
null
小红=100 小明=99 张三=88 李四=60
success