1315

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?

9
  • 21
    Have a look at the npm module "connect". It provides such basic functionality and is the basis of many setups and other packages. Commented May 21, 2011 at 20:53
  • 8
    You should put your solution as an answer and mark it correct. Commented Jun 2, 2011 at 9:04
  • 8
    I was able to find a perfect solution by Eric B. Sowell called Serving static files from node js. Read the whole thing. Highly recommended. Commented Jun 6, 2011 at 6:38
  • 1
    Have a look at a module I wrote called Cachemere. It also automatically caches all your resources. github.com/topcloud/cachemere Commented Nov 25, 2013 at 5:07
  • 1
    local-web-server is a good example to look at Commented May 10, 2014 at 14:45

35 Answers 35

1
2
2

This is one of the fastest solutions i use to quickly see web pages

sudo npm install ripple-emulator -g

From then on just enter the directory of your html files and run

ripple emulate

then change the device to Nexus 7 landscape.

Sign up to request clarification or add additional context in comments.

1 Comment

What has a Nexus 7 todo with this?
2

With Esm module syntax


import http from 'http';
import { parse as parseUrl } from 'url';
import { join as joinPath, extname } from 'path';
import { existsSync, readFileSync, statSync } from 'fs';

const port = process.argv[2] || 4200;

http.createServer(function (request, response) {
    const uri = parseUrl(request.url).pathname;
    let filename = joinPath(process.cwd(), uri);
    const contentTypesByExtension = {
        '.html': 'text/html',
        '.css':  'text/css',
        '.js':   'text/javascript',
        '.json': 'text/json',
        '.svg':  'image/svg+xml'
    };
    if (!existsSync(filename)) {
        console.log( 'FAIL: ' + filename);
        filename = joinPath(process.cwd(), '/404.html');
    } else if (statSync(filename).isDirectory()) {
        console.log( 'FLDR: ' + filename);
        filename += '/index.html';
    }

    try {
        const file = readFileSync(filename, 'binary');
        console.log('FILE: ' + filename);
        const headers = {};
        const contentType = contentTypesByExtension[extname(filename)];
        if (contentType) {
            headers['Content-Type'] = contentType;
        }

        response.writeHead(200, headers);
        response.write(file, 'binary');
        response.end();
    } catch (err) {
        response.writeHead(500, {'Content-Type': 'text/plain'});
        response.write(err + '\n');
        response.end();
    }

}).listen(parseInt(port, 10));
console.log( 'Static file server running at\n  => http://localhost:' + port + '/\nCTRL' +
    ' + C to shutdown');

Comments

1

I can also recommend SugoiJS, it is very easy to set up and gives an option to start writing fast and has great features.

Take a look here to get started: http://demo.sugoijs.com/ , documentation: https://wiki.sugoijs.com/

It has request handling decorators, request policies and authorization policies decorators.

For example:

import {Controller,Response,HttpGet,RequestParam} from "@sugoi/server";
​
@Controller('/dashboard')
export class CoreController{
    constructor(){}
​
    @HttpGet("/:role")
    test(@RequestParam('role') role:string,
         @RequestHeader("role") headerRole:string){
        if(role === headerRole )
            return "authorized";
        else{
            throw new Error("unauthorized")
        }
    }
}

Comments

1

Is very easy with the tons of libraries presents today. Answers here are functional. If you want another version for start faster and simple

Of course first install node.js. Later:

> # module with zero dependencies
> npm install -g @kawix/core@latest 
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static

Here the content of "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" (you don't need download it, i posted for understand how works behind)

// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" 

// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'

var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)

var app = express() 
app.use(express.static(folder)) 
app.listen(8181)
console.log("Listening on 8181")

Comments

0

In order to host Next.js static build with trailingSlash: true & skipTrailingSlashRedirect: true I had to re-implement express.static().

Express.js is nice framework for quick low level prototyping. You could replace it with even low-level Connect.

https://www.reddit.com/r/nextjs/comments/1bcj1ws/hosting_static_files_locally_to_mimicreproduce/

const express = require('express');
const app = express();
const fs = require('fs');

const morgan = require('morgan');
app.use(morgan('dev'));

function isFileExists(p) {
  try {
    return fs.statSync(p).isFile();
  } catch (e) {
    return false;
  }
}

// Emulate express.static(), which suffers from "Express Slashing Syndrome".
app.use("/agent", (req, rsp, next) => {
  const rpath = process.cwd() + "/out" + req.path.split(/[;?]/)[0];
  if (isFileExists(rpath)) {
    rsp.sendFile(rpath);
    return;
  }
  const ipath = rpath + "/index.html";
  if (isFileExists(ipath)) {
    rsp.sendFile(ipath);
    return;
  }
  next();
});

const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
    target: 'http://192.168.1.2:8080',
    changeOrigin: true,
    cookieDomainRewrite: {
        "*": ""
    },
}));

app.listen(process.env.PORT || 3000);

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.