在JavaSrcipt中读取文件时如何处理错误

问题描述 投票:0回答:1

我想在读取文件不正确时记录错误 例如,在下面的代码中,file.txt没有退出并且无法读取它。我想在控制台中看到error5

你能帮我吗?

    const fs = require('fs');
fs.readFile('file.txt', function read(err, data) {
    if (err) {
        throw console.log("error");
    }
});
javascript node.js readfile
1个回答
0
投票

在此代码中,我们使用 err.code 来访问 Node.js 文件系统 (fs) 模块提供的特定错误代码。如果错误代码为“ENOENT”,表示该文件不存在,我们会记录一条自定义错误消息“文件不存在(错误5)”。

当您运行此代码并且文件“file.txt”不存在时,您将在控制台中看到自定义错误消息“文件不存在(错误5)”。

请记住将“file.txt”替换为您要读取的文件的正确路径,并根据需要调整自定义错误消息。此方法可帮助您识别特定的错误场景并使用自定义错误消息进行处理。

这样的代码 const fs = require('fs');

fs.readFile('file.txt', function read(err, data) {
if (err) {
    console.error("Error reading file:", err.code); // Log the error code
    if (err.code === 'ENOENT') {
        console.error("Custom error message: File does not exist (error5)");
    }
}

});

© www.soinside.com 2019 - 2024. All rights reserved.