Home > Software design >  sendFile function in express js is not working
sendFile function in express js is not working

Time:01-21

When i try t run this code, i don't get any error but i get a blank screen when i open loclhost.

const path = require("path")
const express = require("express")

app = express()

app.get("/", (req, res) => {
    let fullpath = path.join(__dirname, './index.html')
    console.log(fullpath)
    res.sendFile(fullpath)
    console.log("File sent")
    res.end()
})

app.listen(5500, () => {
    console.log("Server started")
})

Im using linux, express version is 4.18.2, node version is 18.1.0

I executed the same code in a windows machine with same express version and it worked without any error. Maybe its something to do with linux compatibility or maybe how paths are different in windows and linux.

Things i have tried so far:

const path = require("path")
const express = require("express")

app = express()

app.get("/", (req, res) => {
    let fullpath = path.join(__dirname, './index.html')
    res.sendFile(fullpath, { root: '/' })
    console.log("File sent")
    res.end()
})

app.listen(5500, () => {
    console.log("Server started")
})
const path = require("path")
const express = require("express")

app = express()

app.get("/", (req, res) => {
    var options = {
        root: path.join(__dirname)
    }
    let fileName = 'index.html'
    res.sendFile(fileName, options)
    console.log("File sent")
    res.end()
})

app.listen(5500, () => {
    console.log("Server started")
})

CodePudding user response:

Simple Answer:

  1. Remove res.end();

  2. Try this code

const express = require("express")
app = express()
app.get("/", (req, res) => {
   res.sendFile(__dirname   "/index.html")
   console.log("File sent")  
})

app.listen(5500, () => {
    console.log("Server started")
})

  • Related