Firstly, fs.readFile
is asynchronous function. Which means is not returning the answer instantly or blocks the thread to wait for answer. Instead it requires a callback to let you know when answer is ready.
Secondly, I suggest using path
module to merge __dirname
(the directory name of the current module) and file name to make absolute file paths.
I will provide 3 solutions using different methods.
Solution 1. Using callback method
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileContent = function(path, format, cb) {
fs.readFile(path, format, function(error, contents) {
if (error) throw error;
cb(contents);
});
}
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fileContent(path.join(__dirname, 'page.html'), 'utf8', function (page) {
console.log(page);
res.end(page);
});
}).listen(8080);
Solution 2. Promises using .then
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileContent = function(path, format) {
return new Promise(function (resolve, reject) {
fs.readFile(path, format, function(error, contents) {
if (error) reject(error);
else resolve(contents);
});
});
}
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fileContent(path.join(__dirname, 'page.html'), 'utf8')
.then(function(page) {
console.log(page);
res.end(page);
});
}).listen(8080);
Solution 3. Promise using async/await
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileContent = function(path, format) {
return new Promise(function (resolve, reject) {
fs.readFile(path, format, function(error, contents) {
if (error) reject(error);
else resolve(contents);
});
});
}
var server = http.createServer(async function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var page = await fileContent(path.join(__dirname, 'page.html'), 'utf8');
console.log(page);
res.end(page);
}).listen(8080);