'Read a plain text file inside project file path but get error file not found

I am developing a node.js + typescript project. Here is my project structure:

myapp/
  data.txt
  src/
    helpers/
     worker.ts

So, myapp is the project root, under it there is an src/ directory and a data.txt file, under src there is a helpers/ directory, and my worker.ts is under it.

The data.txt is a plain text.

worker.ts code would like to read the content of that data.txt file. This is the code I tried in worker.ts:

import fs from "fs/promises";

async function readData() {
  const data = await fs.readFile("../../data.txt", "utf-8");
  ...
}

However, when I run it I get error:

[Error: ENOENT: no such file or directory, open '../../data.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '../../data.txt'

Why is that? How to solve it?



Solution 1:[1]

The url passed to readFile is relative to process.cwd() not __dirname.

It is recommended that you use absolute paths. The core module path would give you the ability to build the correct URL for multiple platforms using something like

const path = require('path')
const uri = path.join(__dirname, '..', '..', 'data.txt')

const data = fs.readFileSync(uri, 'utf-8')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1