GithubHelp home page GithubHelp logo

vercel / serve Goto Github PK

View Code? Open in Web Editor NEW
9.2K 98.0 683.0 1.31 MB

Static file serving and directory listing

Home Page: https://npmjs.com/package/serve

License: MIT License

JavaScript 10.48% Shell 0.30% TypeScript 78.69% HTML 10.54%
cli command http node

serve's Introduction

Serve Logo


serve helps you serve a static site, single page application or just a static file (no matter if on your device or on the local network). It also provides a neat interface for listing the directory's contents:

Listing UI

Once it's time to push your site to production, we recommend using Vercel.

Usage

serve v14 onwards requires Node v14 to run. Please use serve v13 if you cannot upgrade to Node v14.

The quickest way to get started is to just run npx serve in your project's directory.

If you prefer, you can also install the package globally (you'll need at least Node LTS):

> npm install --global serve

Once that's done, you can run this command inside your project's directory...

> serve

...or specify which folder you want to serve:

> serve folder-name/

Finally, run this command to see a list of all available options:

> serve --help

Now you understand how the package works! πŸŽ‰

Configuration

To customize serve's behavior, create a serve.json file in the public folder and insert any of these properties.

API

The core of serve is serve-handler, which can be used as middleware in existing HTTP servers:

const handler = require('serve-handler');
const http = require('http');

const server = http.createServer((request, response) => {
  // You pass two more arguments for config and middleware
  // More details here: https://github.com/vercel/serve-handler#options
  return handler(request, response);
});

server.listen(3000, () => {
  console.log('Running at http://localhost:3000');
});

You can also replace http.createServer with micro.

Issues and Contributing

If you want a feature to be added, or wish to report a bug, please open an issue here.

If you wish to contribute to the project, please read the contributing guide first.

Credits

This project used to be called list and micro-list. But thanks to TJ Holowaychuk handing us the new name, it's now called serve (which is much more definite).

Author

Leo Lamprecht (@notquiteleo)

serve's People

Contributors

andybitz avatar avivahl avatar dependabot[bot] avatar disquisition avatar djalmaaraujo avatar dotcypress avatar fmiras avatar gamemaker1 avatar giuseppeg avatar greenkeeper[bot] avatar greenkeeperio-bot avatar icedmonk avatar jameskyburz avatar just-boris avatar justanotherdot avatar leerob avatar leo avatar matheuss avatar mathiasbynens avatar n0v1 avatar pablopunk avatar rauchg avatar rosszurowski avatar schemburkar avatar slorber avatar taravancil avatar timneutkens avatar tohjustin avatar tootallnate avatar wawhal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serve's Issues

cli erroneously says local address is copied to clipboard

The cli output says the local url has been copied to the clipboard, when actually the network url is copied.

If the cli output is correct, then the local url should be what we copy to the clipboard. However, my opinion is that the network url is what should be copiedβ€”given that the stated purpose of serve is to make sharing files over your network easyβ€”in which case the cli output needs to be updated.

Either way, I can put a PR together, just wanted to check in and see which direction fits the needs of the project best!

Why not `localhost:3000`?

@leo I ended up here because I previously used TJ's serve, which ran on localhost:3000. Can you explain your intent behind using 192.168.0.40:<random> instead?

Copying to clipboard is a nice feature that mitigates some of the pain there, but it's easier to get someone up and running with a codebase that uses serve by telling them to just open a browser to e.g. localhost:3000 than to say "npm start, then paste into a new browser window.

Also, running on a random port means that every time you restart, you can't just refresh your browser -- you have to paste in the new address.

I guess I'm mostly responding to having my usual workflow changed just because I npm install served in a new project and was surprised by the changes.

Add feature to serve page.html on requests to site.com/page

Use case

I have a static site built with create-react-app. I'm using react-snapshot which does zero-config SSR by generating html files for each page. The resulting build output is:

build/
   index.html
   history.html
   ...

Unfortunately when serving this directory with list, requests to site.com/history fail. In order to load history.html, I have to request site.com/history.html.

It'd be great if a flag or default feature would be added to support that. πŸ˜ƒ

My current workaround

mkdir build/history
mv build/history.html build/history/index.html

Allow to pass custom path to list

I published my own list with cors support for testing, until it's merged/released

I did use it like that:

12:17 $ ns build -c 'list --cors' -p list-seb
> Deploying /private/var/folders/qm/y2hrgmys1q317t0nfk53mzqm0000gp/T/now-serve-419dd99ce51585c88ee6ec1e97c55117
> Using Node.js 6.9.0 (default)
> Ready! https://ns-edvokxmqio.now.sh (copied to clipboard) [5s]
> Upload [====================] 100% 0.0s
> Sync complete (138B) [3s]
> Initializing…
> Building
> β–² npm install
> Installing package list-seb@latest
> β–² npm start
> Deployment complete!

The problem is that this deployment does not show my files directly, but it shows /node_modules, /content and package.json.

now-server is clever and knows that it has to serve the /content folder instead of the root. It's like to be able to mimic this behavior when using ns with the --command option, so that I can use my own fork in the same way:

ns build -c 'list --cors --path "/content"' -p list-seb 

syntax error on Node v4 (LTS)

heya β–²! list seems to be returning a SyntaxError with node v4.4.0.

/usr/local/lib/node_modules/list/dist/bin/list:220
    const { pathname } = (0, _url.parse)(req.url);
          ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

cheers.

Pass custom items to `ignoredFiles` array

I've noticed that currently ignoredFiles is a hard coded array, and wonder whether there's much value to offering a method to customise the items in this list? The addition of an --ignore flag would suffice.

Serve help doesn't work

When I run serve help, it just tries to serve a help folder in my local directory.

Aka the output becomes serving /Users/admin/Documents/vue-drag-and-drop/help on port 3000

--single breaks now.

It seems like it's throwing when the directory doesn't exist:

if (await pathType.dir(related)) { // ...

This used to work, but now it's broken :(

I'm simply using serve ./build --single and a react-app created app.

Default port 3000

I have been using the old serve library for quite a long time now. I was surprised that this package replaced the one from TJ.

There is one major difference which is quite disturbing for me. The old serve used to listen on port 3000 per default. Couldn't we somehow restore that behavior?

I know that this package copies a URL with the current port to the clipboard. But I liked that I can just stop the server, do something, restart it and the already open tab in the browser just works fine after reloading.

Any thoughts on this request?

Include Default Port

Upgrading from 2.0 to 2.4 breaks my simple use case unless I specify a port.

{
  "start-2.0": "serve dist -s",
  "start-2.4": "serve dist -s -p 3000"
}

It also breaks whether or not the -s flag is present.

RangeError when serving Large (3.6GB) File

node v6.5.0
Serving a 3.6GB File, shows up correctly in browser file list, when I try to download it I get a 500 and micro-list reports:

RangeError: File size is greater than possible Buffer: 0x7fffffff bytes
    at FSReqWrap.readFileAfterStat [as oncomplete] (fs.js:392:11)

Serve not working in Ubuntu 16.04 64bit

Not sure if this is a known issue -- or an issue with my specific configuration -- but even after installing globally in Ubuntu 16.04 64 via:

npm i serve -g

And then running against files in a static directory (a Vue.js build):

serve ./dist

The terminal displays that the server started, gives the two sets of URLs, and then goes right back to the command line.

No errors -- but it immediately stops serving.

Anyone else see this?

(Just as a sanity check, I installed http-server gloabally via npm, ran it against the same static directory, and all is well. Files are served fine via localhost.)

Thoughts?

PS -- Not that it should matter, but I'm running Ubuntu via VMWare on a Windows box with 4 gigs ram to the vm.

cschweda@ubuntu:~/Webdev/test01$ serve dist

   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚                                                     β”‚
   β”‚   Serving!                                          β”‚
   β”‚                                                     β”‚
   β”‚   - Local:            http://localhost:3000         β”‚
   β”‚   - On Your Network:  http://192.168.229.131:3000   β”‚
   β”‚                                                     β”‚
   β”‚                                                     β”‚
   β”‚                                                     β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

cschweda@ubuntu:~/Webdev/test01$ node -v
v7.5.0
cschweda@ubuntu:~/Webdev/test01$ npm -v
4.1.2
cschweda@ubuntu:~/Webdev/test01$ 

Windows Support

Thank you for yet another excellent project.
Is this supported on Windows? I'm trying to run this on Windows 7 64bit and the following error is returned by serve. Any help would be greatly appreciated.

serve -h
or
serve

C:\Users\mattjs\AppData\Roaming\npm\node_modules\serve\dist\bin\serve:163
      const directoryPath = [...pathParts];
                             ^^^

SyntaxError: Unexpected token ...
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

304 caching does not work

Here are 2 deployments with the same file:

You can see that the http-server returns a 304 answer if you ask the file again, while the list implementation always returns 200 with content in any case.

https://github.com/zeit/list/blob/master/bin/list#L242

As far as I see in current implementation, you supply Etags in the answer but you never return 304 on Etag matches (maybe it's intentional and should be handled by now Nginx?), only on "if-modified-since" which is never sent because the server never sends a "last-modified" header.

I think list should support both caching systems, or at least only etags, and return 304 on etags match.

As source of inspiration, you can look at source code of file-server used on http-server that works fine for me
https://github.com/jfhbrook/node-ecstatic/blob/fe17a5623c18319f82101b6549e9e2e526e03d1f/lib/ecstatic.js#L284

(note there's a weak/strong etag subtility, not really sure to understand how it works)

I would be happy to submit a PR if you tell me what kind of behavior you want to support

Bad upgrade path from TJ’s serve

Hallo!

Nice to see serve is having a new function! But I see stuff breaking because I expected it to just be a new version of the package, which is not.

Could you at least give some information if someone is trying to render Jade files and similar that this is not that serve?

Can't set CORS headers

I'm using list/ns to serve my single-page-appication assets (js/css...)

Unfortunatly, the index.html page of my SPA is not a static asset that is in the static deployment: it is a dynamic html page generated by my backend server which is hosted on another domain.

I'd like to set a CORS header, so that my index.html page, served from another domain, is able to load JS assets from the list/ns deployment.

It would be nice to have an option to set custom headers, and a shortcut --cors (like http-server) would also be convenient. Thanks ;)

SyntaxError: Unexpected token {

After npm install -g serve && serve:

const {red} = require('chalk')
      ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:148:18)
    at node.js:405:3

npm version: 3.8.6
running OSX El Capitan v10.11.6

Compatibility of option flags and missing features

Hi there,
I have been long user of serve and what I liked about the server is that it was a simpler alternative to http-server. However, I noticed the latest version of serve is now using different options compared to the last stable version 1.4.0. It seems that now some options are assumed as defaults (like compression enabled by default).

Somehow I prefer to specify explicitly if I want to enable a feature in the server or not, it's a much simpler mental model for using CLIs. I understand there is an ongoing code refactor but not sure why the server options are not backwards compatible?

For example, the latest serve version has the following options:

$ serve --help

  Usage: serve [options] [command]

  Commands:

    help  Display help

  Options:

    -a, --auth       Serve behind basic auth
    -c, --cache <n>  How long static files should be cached in the browser (seconds) (defaults to 3600)
    -o, --cors       Setup * CORS headers to allow requests from any origin (disabled by default)
    -h, --help       Output usage information
    -i, --ignore     Files and directories to ignore (defaults to "")
    -p, --port <n>   Port to listen on (defaults to 3000)
    -s, --single     Serve single page apps with only one index.html
    -u, --unzipped   Disable GZIP compression
    -v, --version    Output the version number   

but version 1.4.0 uses this:

$ serve --help

  Usage: serve [options] [dir]

  Options:

    -h, --help                output usage information
    -V, --version             output the version number
    -a, --auth <user>:<pass>  specify basic auth credentials
    -F, --format <fmt>        specify the log format string
    -p, --port <port>         specify the port [3000]
    -H, --hidden              enable hidden file serving
    -S, --no-stylus           disable stylus rendering
    -J, --no-jade             disable jade rendering
        --no-less             disable less css rendering
    -I, --no-icons            disable icons
    -L, --no-logs             disable request logging
    -D, --no-dirs             disable directory serving
    -f, --favicon <path>      serve the given favicon
    -C, --cors                allows cross origin access serving
        --compress            gzip or deflate the response
        --exec <cmd>          execute command on each request

From looking at the server options, it seems some features are missing from the latest version?

One last thing, there seems to be an inconsistency (or bug) when passing a folder to serve (in latest version):

In serve 2.1.2:

# this doesn't pick up the folder as input
serve --cors ./my-folder 
Running on http://localhost:3000

Hint: check your README.md

Run it

$ serve <path> [options]

In serve 1.4.0:

# this picks up the folder as input
serve --cors ./my-folder 
serving /Users/random/my-folder on port 3000

Using --single with a specified directory

Currently serve does not work with an cmdline option without parameter as the last but one argument and a directory as last argument.
The last but one argument (e.g. --single) then 'eats' the last argument.

Major ?release? PITA

Firstly, stoked for you guys to take the serve name space. As a long time user of npm serve, it's nice to see the package get some new owners and some new love.

That said, depending on async and await for this is a right pain in the ass for one major reason. You're forcing me to nvm use 7 everytime I want to use this library, which instead of meaning I can simply type cd blah/blah && serve I have to type cd blah/blah && nvm use 7 && serve. There in lies the PITA. Especially since most of my projects, and I have many (not publically on this github but on a private enterprise one) projects that are on LTS, switching is doable, but honestly a pain. I would hope you would consider potentially back porting if possible and if not, just supporting node LTS at the very most.

Phew I needed to say that. Now the important stuff.

Serving files like a webserver

I have an html page serving from a nested folder, and it references relative files that don't work.

An example

Html location: http://localhost:53058/some/folder
File location

<!doctype html>
<html>
  <head> <link rel="stylesheet" href="some.css" /> </head>
  <body />
</html>

The serve package currently tries to pull the file from http://localhost:53058/some/some.css, which is incorrect as my file is actually located in this location /some/folder/some.css.

I can work around this issue by appending an additional / to the url, e.g http://localhost:53058/some/folder/ and it fixes the issue but I would have expected this out of the box.

Recommendation

Update the route so that URL's are appended with / by default.

Better info section

This needs to be better. Looks like it's designed for devs (shouldn't be the case)!

screen shot 2017-01-23 at 17 56 08

304s for unmodified files

it would be great if requests for unmodified files got a 304 status code, it would make serving static websites much faster :).

Basic password protection

When using list, you might want to supply a password to protect your directory or static site.

This is especially important when using now-serve to serve a staging environment that should not be reachable by every person on the internet.

Is the cache option actually implemented?

Hi there,

I've installed your package to serve static files and I've set the --cache option but the browser (Chrome or FF) always gets Cache-Control: public, max-age=0 as a response (headers).

I've dug into the code and I've noticed that there isn't any reference to the cache option. Before the release 3.2.8, the code actually covered my use case:

const defaultHeaders = {
    'Cache-Control': 'public, max-age=' + flags.cache,
    Pragma: 'public',
    ETag: getETag(stats)
}

See here

So I'm wondering if during the refactor you wouldn't have deleted that bit by accident?
If that's the case, then you just need to specify the maxAge option for the send package (you call it stream in your code).

ClΓ©ment

Throwing a Syntax Error when deploying static sites with now.

Not sure if is the right place to report it, but trying to deploy a static site using now, the console show this error:

> Initializing…
> Building
> β–² npm install
> β§— Installing:
>  β€£ serve@^3.2.0
> βœ“ Installed 167 modules [14s]
> β–² npm start
> > dist@ start /home/nowuser/src
> > serve ./content
> /home/nowuser/src/node_modules/serve/lib/listening.js:7
> const copyToClipboard = async text => {
>                               ^^^^
> SyntaxError: Unexpected identifier
>     at Object.exports.runInThisContext (vm.js:76:16)
>     at Module._compile (module.js:545:28)
>     at Module._extensions..js (module.js:582:10)
>     at Object.require.extensions.(anonymous function) [as .js] (/home/nowuser/src/node_modules/async-to-gen/register.js:42:5)
>     at Module.load (module.js:490:32)
>     at tryModuleLoad (module.js:449:12)
>     at Function.Module._load (module.js:441:3)
>     at Module.require (module.js:500:17)
>     at require (internal/module.js:20:19)
>     at Object.<anonymous> (/home/nowuser/src/node_modules/serve/lib/index.js:11:19)

Programmatic API and feature request

Hi there !

It is possible to consider the need of silent option ?
Which allow to do not print anything in the console (copy to clipboard too ?)

Then, could it be a way using the Programmatic API to fetch the host and port on the server is running ?
(Not a real need, could be done when options are given).

I am working on a build tool plugin, who have a standardised log.

Cheers,

Add silent mode option

This issue follows #117.

Hi,

Can you add a silent option to the cli, which made Serve does not write anything in the terminal ?

Is this option need to turn off the "copy to clipboard" capabilities too ?

Cheers,

Add url redirects

I'd like to be able to add some url redirects (e.g. 301) to my app. I know this feature is not supported at the moment, but I think it would be a useful addition. I originally submitted this to now-serve

Thanks

Serving files like a webserver

I have an html page serving from a nested folder, and it references relative files that don't work.

An example

Html location: http://localhost:53058/some/folder
File location

<!doctype html>
<html>
  <head> <link rel="stylesheet" href="some.css" /> </head>
  <body />
</html>

The serve package currently tries to pull the file from http://localhost:53058/some/some.css, which is incorrect as my file is actually located in this location /some/folder/some.css.

I can work around this issue by appending an additional / to the url, e.g http://localhost:53058/some/folder/ and it fixes the issue but I would have expected this out of the box.

Recommendation

Update the route so that URL's are appended with / by default.

Syntax error due to async function

Hey there,
serve 3.2.6 doesn't start anymore on node 6.9.4 due to what it looks like failed compilation of async functions.

I tried doing a fresh install with npm rm -g serve && npm i -g serve, but still seeing the error below.

/Users/clemens/.nvm/versions/node/v6.9.4/lib/node_modules/serve/lib/index.js:43
const handler = async (req, res) => {
                      ^
SyntaxError: Unexpected token (
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/clemens/.nvm/versions/node/v6.9.4/lib/node_modules/serve/node_modules/async-to-gen/register.js:40:5)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/clemens/.nvm/versions/node/v6.9.4/lib/node_modules/serve/bin/serve.js:39:1)

edit: sorry, accidentally submitted the issue before writing the actual problem statement :D

gzip support

It would be interesting if it had support gzip compression -z, --gzip
I consider useful for purposes of comparison with the size in production

Add support for .htaccess/htpasswd

There has been cases where the single username+password for http basic auth just isn't enough.

So we should consider adding a full .htaccess/.htpasswd basic auth support to easily allow configuring multiple users with individual passwords.

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.