【问题标题】:How to read image from HTML file with NodeJS?如何使用 NodeJS 从 HTML 文件中读取图像?
【发布时间】:2017-03-14 18:27:04
【问题描述】:

我想读取一个 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/ 时,它会说:

【问题讨论】:

  • 如果您将这一行 response.end(contentFile) 更改为:response.write(contentFile); response.end(); 是否有效?
  • 还是一样的问题。
  • 请在console.log(filePath) 行之前添加:console.log(baseURI.pathName)。结果如何?
  • 嗨@RicardoPontual,它打印undefined
  • 这就是问题所在。尝试像这样设置文件路径进行测试:var filePath=folderPath + '/index.html'

标签: html node.js readfile


【解决方案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!');
});

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2023-03-03
    • 2017-12-04
    • 2019-11-27
    相关资源
    最近更新 更多