GithubHelp home page GithubHelp logo

node-srv's Introduction

Node-srv

Simple fast and static node.js server

Install

$ npm install -g node-srv

Usage

# Start server on port 8000 in current dir
$ node-srv

# Start server on port 8000 in parent dir
$ node-srv ..

# Start server on port 8001 writing logs to *./nodeserver.log* file
$ node-srv --port 8001 --logs ./nodeserver.log

API usage

new Server(options, routes, handlers, exitCallback);

// Require module
var server = require('node-srv');

// Start server
var srv = new Server({
    port: 5000,
    root: '../www/',
    logs: true
});

// Update server port (automatically restert server with new port)
srv.options.port = 5001;

// Stop server
srv.stop();

Options

  • -p, --port [number], port — Port the server is started on (default 8000, or env PORT)
  • -h, --host [host], host — Host or ip address on which the server will work (any host 0.0.0.0 by default)
  • -i, --index [file], index — Sets default index file for directories. For example: for uri /test/, server open test/index.html. Default index.html
  • -l, --logs [path/boolean], logs — Write logs flag. If you specify a path, it will write to that file (if path is folder, default filename will be node-srv.log). Default false
  • -t, --timeout [ms], timeout — Requset timeout (in ms). Default 30000
  • -s, --https [boolean], https — Force create HTTPS server (only with --key and --cert options). Default false
  • --key [path], key — Path to key file for https server
  • --cert [path], cert — Path to certificate file for https server
  • --cors [hosts], cors — Enable CORS. If empty uses * for host. Default false
  • --not-found [path], notFound — Path to 404 error page. Default null
  • --help — print help
  • --version — print version

Usage as Grunt.js task

  1. Install node-srv locally
$ npm i node-srv
  1. Load task into your Gruntfile
grunt.loadTasks('node-srv');
  1. Configure as multitask
grunt.initConfig({
    srv: {
        server1: {
            port: 4001,
            '404': './404.html'
            index: 'index.htm',
            keepalive: false
        },
        server2: {
            port: 4002,
            logs: true
        },
    }
});
  1. Run task
$ grunt srv:server2

Extending server

You can extend server class.

const Server = require('node-srv');

class MyServer extends Server {
    log(string) {
        console.log(string);
    }
}

Handlers

You can add custom handlres specific path patterns (like minimatch).

Parameters way:

const Server = require('node-srv');

new Server({
    // options
    port: 8000
}, {
    // routes
    '**/*.md': 'markdown', // handler name for handlers list
    '_healthcheck': (params, resolve) => { // direct handler function
        resolve({
            body: `OK: ${params.method} ${params.uri}`, // "OK: GET /_healthcheck"
            code: 200,
            headers: {'Content-Type': 'text/plain'}
        });
    }
}, {
    markdown: (params, resolve, reject) => { // handlers key-value list
        markdown.renderFile(params.file).then( html => {
            resolve({
                body: html,
                code: 200,
                headers: {'Content-Type': 'text/html'}
            }, (error) => {
                if (error.code === 'ENOENT') {
                    reject({handler: 'notFound'});
                } else {
                    reject({error});
                }
            });
        });
    }
});

Extend way:

const Server = require('node-srv');

class MyServer extends Server {
    routes() {
        return {
            '**/*.md': 'markdown',
            '_healthcheck': (params, resolve) => {
                ... // as in parameters
            }
        };
    }
    handlers() {
        return {
            markdown: (params, resolve, reject) => {
                ... // as in parameters
            }
        }
    }
}

new MyServer();

You can return HTTP code or Promise object (and resolve HTTP code).

Default handlers:

  • file — response file
  • notFound — response error 404 page (default or optional)
  • timeout — response timeout page (by default on request timeout)
  • serverError — response error 500 page. Define error code by reject({code: 403}) and page will return that.
  • options — response for OPTIONS request method (CORS)

You can override its with any way.

Breaking changes from 2.x to 3.x

CLI options:

  • -r, --root removed. Use arguments: old node-srv --root ../web, new node-srv ../web
  • --404 renamed to --not-found
  • -k shortcut removed from --key. Use only full flag
  • -c shortcut removed from --cert. Use only full flag

Program API:

  • class arguments changed
  • handlers architecture changed

node-srv's People

Contributors

maikudou avatar mojavelinux avatar motorin avatar nim579 avatar ushfnuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

node-srv's Issues

Security issue

Hello,

As a member of the Node.js ecosystem security team I have been reported a security issue regarding this package.

I have made attempts to contact the person identified as maintainer of this package but did not get any answer.

What is the best way to reach someone with commit rights over this repo in order to privately explain what is the issue and resolve it?

Best,

Liran Tal.

Unable to fetch index

I have tried -i index.html, --index index.html or not specifying index at all. I always get a 404:

[2020-04-02T18:31:21.672Z] (+12ms): 404	localhost:5000 GET /	/home/ferrao/Workspace/ac/docs/playbook/public/index.html	(Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36)
❯ ls /home/ferrao/Workspace/ac/docs/playbook/public/index.html
/home/ferrao/Workspace/ac/docs/playbook/public/index.html

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.