Reputation: 34
I have Created a server-side app that can retrieve the index.html file in that directory.
The code is as following,
const http = require('http')
const fs = require('fs')
const port = process.env.PORT || 1337;
const server = http.createServer(function (req, res){
if(req.url.match(/^\/static/))
return respondStatic(req,res)
return respondNotFound(req,res)
});
server.listen(port)
function respondStatic(req,res){
const filename = `${__dirname}/public${req.url.split('/static')[1]}`
fs.createReadStream(filename)
.on('error',()=> respondNotFound(req,res))
.pipe(res)
console.log(req.url);
}
Then run the program and gave the following URL to the browser. http://localhost:1337/static/index.html
After when I see the terminal I have seen that the following code line console.log(req.url);
gave 3 output for me as follows.
/static/index.html
/static/tachyons.min.css
/static/ember.jpg
In that directory, there are 5 files.
chat.css
chat.html
chat.js
ember.jpg
index.html
tachyons.min.css
ember.jpg and tachyons.min.css are using for index.html.
Question is:
Although I gave index.html as static file Why other 2 file( which is /static/tachyons.min.css & /static/ember.jpg prints as req.url in console?
Upvotes: 1
Views: 492
Reputation: 219057
The code doesn't serve only index.html
as a static file, it serves any file in that directory which gets requested. And as you imply here:
ember.jpg and tachyons.min.css are using for index.html
So if index.html
references those other two files, then when you request index.html
in your browser you will also request those other two files. As the code serves those requests, it logs to the console here:
console.log(req.url);
Upvotes: 3