Using node.js as a simple web server

Web Technologies Web Development 3 years ago

9.65K 1 0 0 0

_x000D_ _x000D_ I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same experience as when you read normal web pages). Using the code below, I can read the content of index.html. How do I serve index.html as a regular web page? var http = require('http'); var fs = require('fs'); var index = fs.readFileSync('index.html'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(index); }).listen(9615); One suggestion below is complicated and requires me to write a get line for each resource (CSS, JavaScript, images) file I want to use. How can I serve a single HTML page with some images, CSS and JavaScript?

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago
_x000D_ You can use Connect and ServeStatic with Node.js for this: Install connect and serve-static with NPM $ npm install connect serve-static Create server.js file with this content: var connect = require('connect'); var serveStatic = require('serve-static'); connect().use(serveStatic(__dirname)).listen(8080, function(){ console.log('Server running on 8080...'); }); Run with Node.js $ node server.js You can now go to http://localhost:8080/yourfile.html
0 views
0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum


Q

Unity hosting a custom piece of code on own website [on hold]

_x000D_ _x000D_ I was wondering how would you be able to host an "API" on your own website that you...
Q

I am needing advice on a web bot [on hold]

_x000D_ _x000D_ I want to code a bot that has a GUI or CLI doesn't really matter yet but a GUI would...
Q

date and time picker, that can take a max and min absolute time, compatible with react [on hold]

_x000D_ _x000D_ I have an issue with scheduling things in a web platform (react.js), and need a date...

Important Web Technologies Links