node fs.readFileSync读取文件报找不到路径

如图,server.js想读取public下的index.html文件,却报错。不太清楚是哪里出错了。代码在最下边

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')
})
阅读 20.4k
3 个回答

我是这样解决的。process.cwd(): 总是返回运行 node 命令时所在的文件夹的绝对路径。看这个文章摸索出的解决办法:

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

windows 系统
mac 系统下面,路径是对的哦

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏