gpt4 book ai didi

node.js - 如何正确找到 .txt 文件并使用 NodeJS 读取其内容

转载 作者:行者123 更新时间:2023-12-03 12:34:19 25 4
gpt4 key购买 nike

我正在构建一个 Electron 应用程序,我有一个 logs.txt 文件,我想读取其中的内容并将其放在 HTML 页面上。我正在使用 NodeJS 和“fs”模块,但下面的代码给了我错误“ Uncaught Error :ENOENT:没有这样的文件或目录......”

我认为问题可能在于它的引用。下面是代码:

const fs = require('fs')

fs.readFile('file://' + __dirname + '/logs.txt', function(err, data) {
if (err) throw err;
document.getElementById("main").innerHTML = data;
});

在错误中,它向我显示了文件的确切位置。这是我得到的错误:
Uncaught Error: ENOENT: no such file or directory, open 'file:///Users/MY_USER_ACCOUNT/files/code/git/MY_APP/src/usr/logs.txt'

这正是 logs.txt 文件所在的位置,但由于某种原因,它仍然说那里没有这样的文件。

如果相关的话,我在 Mac 上。

谢谢你。

最佳答案

使用路径,而不是 URL
fs.readFile如果传递了 string,则需要一个文件路径作为论据。

你传给它 file://网址 string反而。删除 file:// .

传递文件的内容编码

您还想将文件的编码传递给 fs.readFile :

const fs = require('fs')
fs.readFile(__dirname + '/logs.txt', 'utf-8', function(err, data) {
if (err) throw err;
document.getElementById("main").innerHTML = data;
});

(您确定要读取 logs.txt 相对于 JavaScript 源文件的位置吗?)

使用 promise
const fsPromises = require('fs').promises;
const data = await fs.readFile(__dirname + '/logs.txt', 'utf-8')
document.getElementById("main").innerHTML = data;

关于node.js - 如何正确找到 .txt 文件并使用 NodeJS 读取其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com