Roy Roy - 1 year ago 126
Node.js Question

Reading local file from absolute path in node fs module

I am trying to read a file from local system using node js 'fs' module. But for some reason, the 'fs' module is not working when I pass absolute path.

Code:

let filePath = "/home/mysystem/dev/myproject/sayHello.txt";
let newFile=fs.readFileSync('file://'+filePath);


The code is throwing an error as:

Uncaught Error: ENOENT: no such file or directory, open 'file:///home/mysystem/dev/myproject/sayHello.txt'


But I can open the file from browser window using the same path.
fs module is working if I pass relative path. I am using this inside an app built using electron framework.

Answer Source

In NodeJS you don't have to use the file protocol for reading files.

You can get rid of the "file://" part and try read the filePath directly

let filePath = "/home/mysystem/dev/myproject/sayHello.txt";
let newFile = fs.readFileSync(filePath);