如何使用 NodeJS 从 HTML 文件中读取图像?

How to read image from HTML file with NodeJS?

我想读取一个 HTML 文件。

我的HTML内容:

<html>
  <hear>
    <title>Learn NodeJS</title>
  </head>

  <body>
    <center>
      <h1>Learn NodeJS with Khuong Pham</h1>
      <img width="400" src="/nodejs.png" />
    </center>
  </body>
</html>

我试过:

const http = require('http')
const fs = require('fs')
const express = require('express')

const app = express()
const folderPath = __dirname + '/public_files'

app.use(express.static(folderPath))

http.createServer(function(request, response) {
  var filePath = folderPath + '/index.html'
  console.log(filePath)

  fs.access(filePath, fs.F_OK | fs.R_OK, function(err) {
    if (err) {
      response.writeHead(404, { 'Content-Type' : 'text/html' })
      response.end('<h1>File not found</h1>')
    } else {
      fs.readFile(filePath, function(err, contentFile){
        if (!err) {
          response.writeHead(200, { 'Content-Type' : 'text/html' })
          response.end(contentFile)
        } else {
          response.writeHead(500, { 'Content-Type' : 'text/html' })
          response.end('<h1>Can not read this content</h1>')
        }
      })
    }
  })
}).listen(3500)

但是当我访问 http://localhost:3500/ 时,它显示:

您在这里混合了两种方法。首先,您尝试使用 express,但后来您使用 http.createServer 启动自己的服务器,而应该使用 express 来这样做。

您的 js 应该类似于下面的内容。没有测试下面的代码。适当地编辑它。这只是为了展示这个想法。

const http = require('http')
const fs = require('fs')
const express = require('express')

const app = express()
const folderPath = __dirname + '/public_files'

//mount your static paths
// renders your image and index.html
app.use(express.static(folderPath))

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

//mount your other paths
// in this case render 404.
app.get("*",function (req, res) {
  res.status(404).send(''<h1>File not found</h1>'');
});

//start the server.
app.listen(3500, function () {
 console.log('Example app listening on port 3500!');
});