How to read a. txt file in Electron?

Asked

Viewed 371 times

0

I’m trying to read all the contents of a file .txt through Electron possessing the following files:

script / index.js

index.html

file.txt

package json.

index js.

const fs = require('fs');

function read_file(){
    try {
        var data = fs.readFileSync('../file.txt', 'utf8');
        console.log(data.toString());
    } catch(e) {
        console.log('Error:', e.stack);
    }
}

HTML

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Reading File</title>
        <script src="script/index.js"></script>
    </head>
    <body>
        <button type="button" name="button" onclick="read_file()">Click me</button>
    </body>
</html>

When executing the HTML Button, this error appears:

Error: Error: ENOENT: no such file or directory, open '.. /file.txt'

What’s wrong with this code that you can’t read the file via console?

  • And if you take the ../ from the file path, what happens?

  • It worked here, but why did I need to take this one (../) ? Because what came to mind was for index.js to read the previous directory.. how strange

2 answers

2


No use reading absolute or relative paths, the file is inside the "app" (in assets, usually packaged in .asar READ: https://electronjs.org/docs/tutorial/application-packaging)

By logic (I am without Lectron on this machine, I will edit as soon as possible), just do not use the ../ because the file.txt is at the same level as the application.

But it’s likely that to avoid any kind of problem using the absolute path will help, but for that you need to know where it starts, you can even use something like:

a/b/c/d/e/f.txt

But you can also choose to use __dirname, something like:

fs.readFileSync('file://' + __dirname + '/file.txt', 'utf8');

Which I think will make it a lot easier, especially if you use the .asar

1

Apparently the path you are passing to open does not exist.

Use absolute and non-relational paths to avoid this type of failure.

Examples

I want to open a file on my home, /home/user/file.txt

I want to open a file on my Desktop, /home/user/Desktop/file.txt

I want to open a file in the same folder, I am running the program ./file.txt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.