I
I
Ingerniated2016-10-12 12:24:08
Node.js
Ingerniated, 2016-10-12 12:24:08

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

2 answer(s)
I
Ivan, 2016-10-12
@LiguidCool

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

PS
I strongly do not advise you to start picking Express without understanding the native basics!

I
Ilnur Ibautllin, 2016-10-13
@ilnuribat

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 question

Ask a Question

731 491 924 answers to any question