Reputation: 343
I'm sorry to ask such a simple question. I've been sent files by someone, an index.html file which pulls in a js file within script
tags. I have to start a webserver to get through authentication and view the files (am in dev).
In my CLI i have navigated to the directory containing index.html. I have checked with node -v
that I have it installed globally (yes, v 8.6). I've run the simple command node
and checked my browser at http://localhost:3000 and a few other ports but get no joy. I've also tried node index.html
but CLI throws an error.
How do i start the webserver? All the examples online tell me to build a .js file, but this is not an option.
Upvotes: 0
Views: 486
Reputation: 38529
Yes, this is possible.
A very simple example of how to do this would be to create file, let's call it app.js
and put this in it:
const http = require('http'), // to listen to http requests
fs = require('fs'); // to read from the filesystem
const app = http.createServer((req,res) => {
// status should be 'ok'
res.writeHead(200);
// read index.html from the filesystem,
// and return in the body of the response
res.end(fs.readFileSync("index.html"));
});
app.listen(3000); // listen on 3000
Now, run node app.js
Browse to http://localhost:3000
There's loads of other npm packages that will help you out do this, but this is the simplest 'pure node' example to literally read index.html and serve it back as the response.
Upvotes: 1
Reputation: 582
Since you don't want to build a backend but just an http server. I would propose to use an npm package that do just what you need:
Open a console
npm install http-server -g
Go to your "index.html" folder (in the console) then type:
http-server
Then reach your content in your browser at this address:
http://localhost:8080
Documentation here: https://www.npmjs.com/package/http-server
Upvotes: 1
Reputation: 1138
Steps to set up a node web server
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/www'));
app.listen('3000');
console.log('working on 3000');
Index.html
<!doctype html
<html>
<head>
<title> my local server </title>
</head>
<body>
<h1> server working </h1>
<p> just put your html,css, js files here and it work on your own local nodejs server </p>
</body>
</html>
Go to the project root path and take the command prompt, then start the server by running the command node server.js
Then go to the browser and run the url localhost:3000.
Now you can see the html page will render on your browser.
Upvotes: 3
Reputation: 18657
Its very easy to start a server using node js
Create a server.js
file,
const http = require('http')
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(3000);
Run node server.js
This will even solve your backslash issue by this
Upvotes: 0