0
votes

I want to make a simple server so I can serve local html and JS files while developing.

I tried to get a node app to just take whatever is in the URL, and respond with the page, but no luck (here's my attempt with express).

var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use(app.router); //use both root and other routes below
app.use(express.static('c:\\users\\pete\\projects\\')); //use static files in ROOT/public folder

app.get("/*", function(req, res){ //root dir
  fs.readFile(req.path, function(err,html){
    if(err){
        console.log(err);
        return;
    }
    res.write(html);
    res.end();
  });
});

app.listen(port, host);

but this always looks for the file at c:\, not the correct path.

I've also tried http-server for a simple static server, but it is always crashing when serving js files. https://github.com/nodeapps/http-server

I need to be able to serve your basic html,css,js files simply, and hopefully from any path provide in the URL. This is just for local front-end development. Any help?

3

3 Answers

5
votes

You should give complete path for fs.readFile

fs.readFile('c:\\users\\pete\\projects\\'+req.path, function(err,html){

or you can just do

var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use('/', express.static('c:\\users\\pete\\projects\\'));
app.listen(port, host);
0
votes

If you are intrested in ultra-light http server without any prerequisites you should have a look at: mongoose you can server your files with and it's less than 10MB

0
votes

If you are looking for light web server in node which can do:

  • serving static files (static html, js, css, images)
  • executing index.js JS files in node on server side
    (index.js in your document root or in any folder)
  • realoding your index.js apps on change or on error
  • executing any given JS functions
  • optional displaying folder content
  • optional error pages
  • optional handling socket.io packets, session and more

You can check out project Web Development Node.js Server

There are few working demos you can start with:

  • Hello world
    the easiest example, static and dynamic content serving
  • Chat in Angular 1
    static content, dynamic HTTP request, websocket requests, client side in Angular.JS 1
  • Chat in pure JS
    the most complex example, static content, dynamic HTTP request, websocket requests

The server class is possible to extend in standard javascript way,
so you can do anything to customize the behaviour.

The source code is short and easy to understand and it can do mostly
everything, what beginners need with webserver.