Khuong Khuong - 1 month ago 9
HTML Question

How to read image from html file with NodeJS

I want to read html file.

enter image description here

My html content:

<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>


I've tried:

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)


But when I access
http://localhost:3500/
, it says:

enter image description here

Please help me with this. Thanks

Answer

You are mixing two methods here. Firstly you are trying to use express, but later you are starting your own server using http.createServer Instead you should use express to do so.

Your js should be something similar to below. Have not tested below code. Edit it approiately. This is just to show the idea.

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!');

});

Comments