0

i'm trying to display a html page creating a node http server, when i try to take the code of the html file it returns undefined, this is the code...

var http = require('http');

var fileContent = function(path, format) {
  var fs = require('fs');
  fs.readFile(path, format, function(error, contents) {
    if (error) throw error;
    return contents;
  });
}

var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  page = fileContent('./page.html','utf8');
  console.log(page);
  res.end(page);
}).listen(8080);

i printed the error,

[Error: ENOENT: no such file or directory, open './page.html'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: './page.html'
}

the two files are in the same directory

1 Answers1

1

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);
TheMisir
  • 4,083
  • 1
  • 27
  • 37