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

时间:2016-11-01 15:18:58

标签: html node.js readfile

我想阅读HTML文件。

enter image description here

我的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/时,它会说:

enter image description here

1 个答案:

答案 0 :(得分:1)

你在这里混合两种方法。首先,您尝试使用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!');
});