A
A
Artem Melnykov2019-02-27 07:18:19
JavaScript
Artem Melnykov, 2019-02-27 07:18:19

How to open a separate html file in response.write(``);?

There is a code:

var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("<h1>Привет!</h1><p>Вы запросили `" +
request.url + "`</p>");
response.end();
});
server.listen(8000);

It is impossible to make it so that instead of there is a path to the index.html file, which is located in the same directory with the script? Tried to do with fs did not work. response.write("");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Esin, 2019-02-27
@NickProgramm

Why didn't you succeed with fs? Should work

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, { encoding: 'utf-8' }, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question