Answer the question
In order to leave comments, you need to log in
How to implement statics on the server?
Could you tell me how to implement statics to this code?
var http = require("http");
var fs = require("fs");
http.createServer(function(request, response) {
fs.readFile("index.html", {encoding: "utf-8"}, function(error, file) {
response.writeHead(200, {"Content-type" : "text/html"});
response.write(file);
response.end();
});
}).listen(8000);
Answer the question
In order to leave comments, you need to log in
Well, take the path to the file from the request and substitute it in the readout.
let http = require("http");
let fs = require("fs");
http.createServer(function(request, response) {
console.log(request.url);
fs.readFile('.' + request.url, (err, data) => {
if (err){
response.writeHead(404, {"Content-type" : "text/html"});
response.write('File not found');
response.end();
console.log(err);
} else {
response.writeHead(200, {"Content-type" : "text/html"});
response.write(data);
response.end();
}
});
}).listen(8000);
Since you have just started creating a server, it would be better to switch to Express, where all the statics are given in one line,
where all files for output are stored in the public folder - index.html, javascript, css.
Link
Full code:
var express = require('express');
var app = express();
app.use(express.static('public'));
app.listen(8000, function() {
console.log("Server started at " + 8000 + " port");
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question