user12270832
user12270832

Reputation:

How can I correctly find a .txt file and read it's contents using NodeJS

I am building an Electron application and I have a logs.txt file which I want to read the contents of and put it on an HTML page. I'm using NodeJS and the "fs" module but the following code is giving me the error "Uncaught Error: ENOENT: no such file or directory..."

I think the issue may lie in the reference of it. Here's the code below:

const fs = require('fs')

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

In the error it shows me the exact location of the file. Here's the error I'm getting:

Uncaught Error: ENOENT: no such file or directory, open 'file:///Users/MY_USER_ACCOUNT/files/code/git/MY_APP/src/usr/logs.txt'

This is exactly where the logs.txt file is, but for some reason it still says that there's no such file there.

I'm on a Mac if that is relevant.

Thank you.

Upvotes: 0

Views: 1370

Answers (2)

Always Learning
Always Learning

Reputation: 5581

If you are using the file:// format, you need to create a URL object to pass to fs.readFile() like this rather than just passing it as a string:

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

See the documentation here

Upvotes: 0

AndreasPizsa
AndreasPizsa

Reputation: 1746

Use a path, not a URL

fs.readFile expects a file path if passed a string as argument.

You’re passing it a file:// URL string instead. Remove file://.

Pass the file’s content encoding

You also want to pass the file’s encoding to 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;
});

(Are you sure you want to read logs.txt relative to the location of your JavaScript source file?)

Use Promises

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

Upvotes: 1

Related Questions