node.jsexpress

Node.js + Express.js: How to use the root (/) for serving static files?


how do we serve a static file located in the root of the directory (/) and not in a folder of it? I am using Node.js with Express.js, I have tried the following JavaScript code in my index.js file which is located in / (the root of the directory).

Attempt 1

const path = require('path');

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
})

Attempt 2

const path = require('path');

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/'));
})

Same output as Attempt 1

Attempt 3

app.use(express.static('/'));

Attempt 4

app.use(express.static(''));

Please assist, I have refered to many other possible questions similar to this, and one of the questions didn't have an answer, so I am re-asking.


Solution

  • There isnt any difference if you use / and no / in the script

    for express use

    app.use(express.static(process.cwd() + '/'));