I have a little problem, I'm trying to read a .txt
file in node.js app using fs library.
My directory tree looks like this:
app/controller/appController.js
app/data/string.txt
My code in appController script looks like this:
const fs = require('fs')
let data = fs.readFileSync('../data/string.txt', 'utf8');
and I'm getting error:
Error: ENOENT: no such file or directory, open '../data/string.txt'
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: '../data/string.txt'
Naturally, I've installed fs library.
I was trying conver including fs library to ES module.
import { readFileSync } from 'fs';
but it doesn't work.
When I've moved .txt file to directory where is appController it's still not working.
Relative file paths are resolved with the current working directory for the process, not with the directory of the module your code is in.
You can resolve a path relative to the module directory (in a CommonJS module) by using __dirname
(which is the current module's path) like this:
let data = fs.readFileSync(__dirname + '/../data/string.txt', 'utf8');