Node fs.readFileSync read file report could not find path

as shown in the picture, server.js tried to read the index.html file under public, but reported an error. I"m not sure what went wrong. The code is at the bottom

Error: ENOENT: no such file or directory, open "\public\index.html"
    at Object.openSync (fs.js:434:3)
    at Object.readFileSync (fs.js:339:35)
    at Object.eval (webpack:///./src/server/index.js?:27:19)
    at eval (webpack:///./src/server/index.js?:54:30)
    at Object../src/server/index.js (E:\Code\web\ssr\react-music\build\server.js:4673:1)
    at __webpack_require__ (E:\Code\web\ssr\react-music\build\server.js:20:30)
    at E:\Code\web\ssr\react-music\build\server.js:84:18
    at Object.<anonymous> (E:\Code\web\ssr\react-music\build\server.js:87:10)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)

clipboard.png

import express from "express"
import routes from "../routes"
import serverRender from "./render"
import fs from "fs";
import path from "path";
const app = express()
const template = fs.readFileSync(path.resolve(__dirname,"../public/index.html"),"utf8")
console.log(template);
app.use(express.static("public"))
app.get("*", (req, res) => {
  res.send(serverRender(req, routes))
})

app.listen(3000, () => {
  console.log("server listening on port 3000")
})
Oct.21,2021

this is how I solved it. Process.cwd (): always returns the absolute path to the folder where the node command was run. Take a look at this article to find a solution:

  const template = fs.readFileSync(process.cwd() + '/public/static/index.html', 'utf8')

path.join(__dirname,"../public/index.html")

windows system
under mac system, the path is right

Menu