How to use serve-static - 10 common examples

To help you get started, we’ve selected a few serve-static examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github raymondsze / create-react-scripts / packages / example-universal-react-app / src / server.js View on Github external
const ASSETS_PATH = path.join(process.cwd(), 'build/assets.json');
const DLL_ASSETS_PATH = path.join(process.cwd(), 'build/dll-assets.json');

console.log('Waiting client-side bundling...');
while (!fs.existsSync(ASSETS_PATH));

const assets = {
  ...JSON.parse(fs.readFileSync(DLL_ASSETS_PATH)),
  ...JSON.parse(fs.readFileSync(ASSETS_PATH)),
};

const app = express();

if (process.env.NODE_ENV === 'production') {
  app.use(serveStatic(path.join(process.cwd(), 'build/client'), { index: false }));
}

app.get('*', async (req, res) => {
  console.log('SeverSideRendering');
  // we don't need to care css or js stuff as already included in data
  // but if we want dynamic html page, we could use the assets variable from the above
  // render the component to root div
  res.set('content-type', 'text/html').send(
    ReactDOMServer.renderToStaticMarkup(
github fooey / gw2w2w-react / routes / statics.js View on Github external
/*
    *
    * Static Routes
    *
    */

    const staticOptions = {
        dotfiles   : 'deny',
        etag       : true,
        maxAge     : '1d',
        // index   : false,
        // redirect: true,
    };

    app.use(serveStatic('public', staticOptions));
    app.use('/nm', serveStatic(process.cwd() + '/node_modules', staticOptions));
    app.use('/node_modules', serveStatic(process.cwd() + '/node_modules', staticOptions));
    app.use('/routes', serveStatic(process.cwd() + '/routes', staticOptions));
    app.use('/views', serveStatic(process.cwd() + '/views', staticOptions));

    express.static.mime.define({
        'text/plain': ['jade', 'map'],
        'text/css'  : ['less'],
        'text/jsx'  : ['jsx'],
    });

};
github nuxt / nuxt.js / packages / server / src / server.js View on Github external
// For serving static/ files to /
    const staticMiddleware = serveStatic(
      path.resolve(this.options.srcDir, this.options.dir.static),
      this.options.render.static
    )
    staticMiddleware.prefix = this.options.render.static.prefix
    this.useMiddleware(staticMiddleware)

    // Serve .nuxt/dist/client files only for production
    // For dev they will be served with devMiddleware
    if (!this.options.dev) {
      const distDir = path.resolve(this.options.buildDir, 'dist', 'client')
      this.useMiddleware({
        path: this.publicPath,
        handler: serveStatic(
          distDir,
          this.options.render.dist
        )
      })
    }

    // Dev middleware
    if (this.options.dev) {
      this.useMiddleware((req, res, next) => {
        if (!this.devMiddleware) {
          return next()
        }
        this.devMiddleware(req, res, next)
      })

      // open in editor for debug mode only
github ustccjw / tech-blog / server / route / index.js View on Github external
const route = app => {
	// public resource
	app.use(favicon(path.join(ROOT, 'public/favicon.ico')))
	app.use(serveStatic(path.join(ROOT, 'public'), { maxAge: '1d' }))
	app.use(serveStatic(path.join(ROOT, 'dist'), { maxAge: '1d' }))

	// route
	app.use('/model.json', falcorMiddleware.dataSourceRoute((req) =>
		new ModelRouter(req.cookies.userId)))

	const templatePath = ENV === 'development' ?
		path.join(ROOT, 'view/dev-index.html') :
		path.join(ROOT, 'view/index.html')

	// default index
	app.get('*', (req, res, next) => {
		match({ routes, location: req.url },
			async (err, redirect, renderProps) => {
				try {
					if (err) {
						throw err
github nuxt / nuxt.js / lib / core / renderer.js View on Github external
// For serving static/ files to /
    const staticMiddleware = serveStatic(
      path.resolve(this.options.srcDir, this.options.dir.static),
      this.options.render.static
    )
    staticMiddleware.prefix = this.options.render.static.prefix
    this.useMiddleware(staticMiddleware)

    // Serve .nuxt/dist/ files only for production
    // For dev they will be served with devMiddleware
    if (!this.options.dev) {
      const distDir = path.resolve(this.options.buildDir, 'dist')
      this.useMiddleware({
        path: this.publicPath,
        handler: serveStatic(distDir, {
          index: false, // Don't serve index.html template
          maxAge: '1y' // 1 year in production
        })
      })
    }

    // Add User provided middleware
    this.options.serverMiddleware.forEach(m => {
      this.useMiddleware(m)
    })

    // Finally use nuxtMiddleware
    this.useMiddleware(nuxtMiddleware.bind(this))

    // Error middleware for errors that occurred in middleware that declared above
    // Middleware should exactly take 4 arguments
github collab-project / videojs-record / scripts / server.js View on Github external
import connect from 'connect';
import path from 'path';
import portscanner from 'portscanner';
import serveStatic from 'serve-static';

// Configuration for the server.
const PORT = 9999;
const MAX_PORT = PORT + 100;
const HOST = '127.0.0.1'

const app = connect();

// update mimetype
serveStatic.mime.define({'application/wasm': ['wasm']});

app.use(serveStatic(path.join(__dirname, '..')));

portscanner.findAPortNotInUse(PORT, MAX_PORT, HOST, (error, port) => {
    if (error) {
        throw error;
    }

    process.stdout.write(`Serving on http://${HOST}:${port}` + '\n\n');

    app.listen(port);
});
github mattdesl / budo / lib / middleware.js View on Github external
var logger = require('./simple-http-logger')
var urlLib = require('url')
var xtend = require('xtend')
var pushState = require('connect-pushstate')
var liveReload = require('inject-lr-script')
var urlTrim = require('url-trim')
var escapeHtml = require('escape-html')

var fs = require('fs')
var browserify = require('browserify')
var path = require('path')
var liveReloadClientFile = path.resolve(__dirname, 'reload', 'client.js')
var bundledReloadClientFile = path.resolve(__dirname, '..', 'build', 'bundled-livereload-client.js')

// Patch 'wasm' since send has not yet been updated to latest 'mime' module
serveStatic.mime.types['wasm'] = 'application/wasm'

module.exports = budoMiddleware
function budoMiddleware (entryMiddleware, opts) {
  opts = opts || {}
  var staticPaths = [].concat(opts.dir).filter(Boolean)
  if (staticPaths.length === 0) {
    staticPaths = [ process.cwd() ]
  }

  var entrySrc = opts.serve
  var live = opts.live
  var cors = opts.cors
  var handler = stacked()
  var middlewares = [].concat(opts.middleware).filter(Boolean)

  // Everything is logged except favicon.ico
github ff0000-ad-tech / wp-creative-server / routes / browse.js View on Github external
(req, res, next) => {
			const type = serveStatic.mime.lookup(req.url)
			// build paths:
			if (req.url.indexOf(utils.BUILD_FOLDER) > -1) {
				return serveStatic(global.servePath, {
					// let folders with index.html pass through
					index: false,
					// render html files as plain text
					setHeaders: (res, path) => {
						if (type === 'text/html') {
							res.setHeader('Content-Type', 'text/plain')
						}
					}
				})(req, res, next)
			} else {
				// all other assets serve static
				return serveStatic(global.servePath)(req, res, next)
			}
github GoogleChromeLabs / gulliver / app.js View on Github external
app.use((req, res, next) => {
  const path = req.url;
  req.url = asset.decode(path);
  let mime = serveStatic.mime.lookup(req.url);
  if (mime.match('image*') || req.url.includes('manifest.json')) {
    res.setHeader('Cache-Control', 'public, max-age=' + CACHE_CONTROL_EXPIRES);
  } else if (req.url === path) {
    res.setHeader('Cache-Control', 'public, max-age=' + CACHE_CONTROL_SHORT_EXPIRES);
  } else {
    // versioned assets don't expire
    res.setHeader('Cache-Control', 'public, max-age=' + CACHE_CONTROL_NEVER_EXPIRE);
  }
  staticFilesMiddleware(req, res, next);
});
github binary-com / webtrader / tests / server.js View on Github external
export const start = () => {
  app = connect()
    .use(serveStatic('dist/uncompressed'))
    .listen(3000);
  console.log('\n\x1b[1;32mConnected web server on http://localhost:3000\x1b[m')
};
export const close = () => {

serve-static

Serve static files

MIT
Latest version published 2 months ago

Package Health Score

89 / 100
Full package analysis