Home > Software design >  [Node.js]How to access files in different directory using readFile
[Node.js]How to access files in different directory using readFile

Time:02-22

Under directory main:

  • css(foler)
    • stylesheet.css
  • js(folder)
    • data.js
    • server.js
  • index.html

And inside server.js:


    //Cannot access index.html
    file.readFile('index.html', 'utf8', function(err, contents){
      //some code
    });

Specifically, how do we access stylesheet.css and index.html

CodePudding user response:

For accessing folders on a top level directory you can use .. in your path.

Access index.html in server.js

//access top level directory using `..`
file.readFile('../index.html', 'utf8', function(err, contents){
  //some code
});

file.readFile('../css/stylesheet.css', 'utf8', function(err, contents){
  //some code
});

Ideally you would always import from absolute paths. That prevents breaking your app when you restructure it. I suggest to always start your app from the root directory of your project like node js/server.js .

When starting it from root the process.cwd() (current working directory.) variable will always point to the root dir of the project and file reads could be done using:

var { join } = require('path')
var htmlFile = join(process.cwd(), 'index.html')
var cssFile = join(process.cwd(), 'css', 'stylesheet.css')

// read html file
file.readFile(htmlFile, 'utf8', function(err, contents){
  //some code
});

// ...

CodePudding user response:

when you start the server, a global variable called __dirname is set that holds the absolute path of the folder that server.js is inside. Now we can use that value to read files relative to server.js file. In the following code, I used path.join() to construct the path to the files that you want to access. The double dots (..) is the directory above the js folder.

const fs = require("fs");
const path = require("path");

// Get the absulote path of the files
const htmlFile = path.join(__dirname, "..", "index.html");
const cssFile = path.join(__dirname, "..", "css", "stylesheet.css");

// Read files
fs.readFile(htmlFile, "utf8", function (err, content) {
  console.log(content);
});

fs.readFile(cssFile, "utf8", function (err, content) {
  console.log(content);
});

CodePudding user response:

Try add ".", so it will be :

fs.readFile("./../index.html", "utf8", (err, content){ return }) 
  • Related