Cannot find file in Node even though it has correct path

I'm guessing you're confusing the current working directory of your script for the location of your script. It's hard to say without knowing the structure of your project and where you're calling the script from.

Assuming your shell's working directory is /, .dburl is at /.dburl and your script is located at /foo/bar/script.js. If you run node foo/bar/script, you could read .dburl with readFileSync('./dburl'). However if you run cd foo/bar; node ./script, you would need to read .dburl with readFileSync('../../.dburl').

This is because the working directory of your script is equal to the working directory of the shell you launched it in.


READING FILE ON SAME LEVEL

enter image description here

 //the server object listens on port 8080
    const PORT = 8080;
    var http = require("http");
    var fs = require("fs");
    var path = require("path");

    //create a server object:
    http
      .createServer((req, res) => {
        console.log("READING FILE: ", path.resolve(__dirname, "input.txt"));

        fs.readFile(path.resolve(__dirname, "input.txt"), (err, data) => {
          //error handling
          if (err) return console.error(err);

          //return file content
          console.log("FILE CONTENT: " + data.toString());
          res.write(data.toString());
          res.end();
          console.log("READ COMPLETED");
        });
      })
      .listen(PORT);

READING FILE ON OTHER LEVEL:

enter image description here

//the server object listens on port 8080
const PORT = 8080;
var http = require("http");
var fs = require("fs");
var path = require("path");

//create a server object:
http
  .createServer((req, res) => {
    console.log("READING FILE: ", path.resolve(__dirname, "./mock/input.txt"));

    fs.readFile(path.resolve(__dirname, "./mock/input.txt"), (err, data) => {
      //error handling
      if (err) return console.error(err);

      //return file content
      console.log("FILE CONTENT: " + data.toString());
      res.write(data.toString());
      res.end();
      console.log("READ COMPLETED");
    });
  })
  .listen(PORT);

You can use the module-level variable __dirname to get the directory that contains the current script. Then you can use path.resolve() to use relative paths.

console.log('Path of file in parent dir:', require('path').resolve(__dirname, '../app.js'));

Tags:

Node.Js

Fs