简体   繁体   中英

Confusion about http-server vs using http in NodeJS

I'm trying to run an html file using NodeJS. I installed a command line node package called "http-server". When I run the html file using http-server, it opens just fine.

Where the problems start arising for me is when I try to host the same html file using NodeJS's html library. I tried running my html file using the code below, but it does not work as I would expect. The webpage is just a blank white page.

Why is this? What does the http-server package do that my regular code does not do?

Thank you for any help in advance!

var http = require('http');
var fs = require('fs');

var html = fs.readFileSync('index.html');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(html);
}).listen(8000);

Replace fs.readFileSync('index.html'); with fs.readFileSync(__dirname + '/index.html'); (__dirname is the directory the project is in)

It seemed that I was not including some of the necessary files when I was creating my NodeJS file. The code below solved my issue!

app.use(express.static(path.join(__dirname, 'FOLDER_NAME')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM