How to use the compression function in compression

To help you get started, we’ve selected a few compression 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 stipsan / epic / src / server / web / worker.js View on Github external
export const run = worker => {
  const app = express()
  const redis = createConnection(process.env.REDIS_URL || '127.0.0.1:6379')

  /* eslint no-console: "off"*/
  console.log('connecting to redis on', process.env.REDIS_URL || '127.0.0.1:6379')

  // Security reasons, this should be the default in express
  app.set('x-powered-by', false)
  // We are on Heroku after all, behind load balancers
  // and want our https and wss to work properly with the IPs
  app.enable('trust proxy')

  app.use(compressionMiddleware())
  app.use(originsMiddleware())
  /*
  if(process.env.NODE_ENV !== 'production') {
    const config   = require('../../webpack.config');
    const compiler = require('webpack')(config);
    app.use(require('webpack-dev-middleware')(compiler, config.devServer));
    //@TODO the socket.io that the middleware uses breaks on SocketCluster
    app.use(require('webpack-hot-middleware')(compiler));
  }
  //*/
  app.use(express.static('public', { maxAge: 86400000 * 365, index: false }))
  app.use(htmlMiddleware())

  worker.httpServer.on('request', app)

  createSocketServer(worker.scServer, redis)
github yrahul3910 / video-sharing-site / server / server.js View on Github external
import formidable from "formidable";
import fs from "fs-path";

// Used for transpiling
import webpack from "webpack";
import config from "../webpack.config";

import dbUtils from "./db.js";

const port = 8000;
const app = express();
const compiler = webpack(config);
dotenv.config();

// gzip files
app.use(compression());
app.use(session({secret: process.env.SESSION_SECRET}));
app.use(bodyParser.json());
app.use(bodyParser({extended: true}));
app.use(cors());
// Use Webpack middleware
app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.get("/*", (req, res) => {
    res.sendFile(path.join(__dirname, "../src/index.html"));
});

app.post("/api/upload", (req, res) => {
    res.writeHead(200, {"Content-Type": "application/json"});
github DevAlien / dripr-ui / src / server / index.js View on Github external
import {fork} from 'child_process';

// Create a server
const server = express();
const NODE_ENV = server.get('env');
const PRODUCTION = NODE_ENV === 'production';
const argv = minimist(process.argv.slice(2));
const PORT = argv.port || 4000;

// Middleware
server.use(morgan(PRODUCTION ? 'combined' : 'dev'));
server.use(bodyParser.json());
server.use(cookieSession({
  keys: ['secret1', 'secret2']
}));
server.use(compression());
server.use(csurf());

if (PRODUCTION){
  // On production, use the public directory for static files
  // This directory is created by webpack on build time.
  server.use(serveStatic(path.join(__dirname, '../../public'), {
    maxAge: 1000 * 60 * 60 * 24 * 30, // 1 month
    index: false
  }));
} else {
  // On development, serve the static files from the webpack dev server.
  fork(require.resolve('./webpack'));
}

// Render the app server-side and send it as response.
server.get('/*', require('./render'));
github olymp / olymp / universally / src / server / index.js View on Github external
import offlinePage from './middleware/offlinePage';
import errorHandlers from './middleware/errorHandlers';
import config from '../../config';
import session from 'express-session';

// Create our express based server.
const app = express();

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

// Security middlewares.
app.use(...security);

// Gzip compress the responses.
app.use(compression());

// When in production mode, we will serve our service worker which was generated
// by the offline-plugin webpack plugin. See the webpack plugins section for
// more information.
// Note: the service worker needs to be served from the http root of your
// application for it to work correctly.
if (process.env.NODE_ENV === 'production'
  && config.serviceWorker.enabled) {
  app.get(`/${config.serviceWorker.fileName}`, serviceWorker);
  app.get(
    `${config.bundles.client.webPath}${config.serviceWorker.offlinePageFileName}`,
    offlinePage,
  );
}

// Configure serving of our client bundle.
github nightwolfz / mobx-starter / src / server / index.js View on Github external
import todos from './routes/todos'
import account from './routes/account'

const app = express()

// Serve static files
if (isArray(config.http.static)) {
    config.http.static.forEach(staticRoute => {
        logger('inferno:static')(staticRoute.path)
        app.use(staticRoute.url, express.static(staticRoute.path))
    })
}

// Config
app.disable('x-powered-by')
app.use(compression())

// Middleware
app.use(favicon(config.http.favicon))
app.use(bodyParser.json({ limit: '2mb' }))
app.use(bodyParser.urlencoded({ limit: '2mb', extended: true }))

// Needed for authentication
app.use(cookieParser())
app.use(context)

// Routes
app.use(todos)
app.use(account)
app.use(render)

app.listen(config.http.port, function() {
github strues / react-universal-boiler / src / server.js View on Github external
import RouterContext from 'react-router/lib/RouterContext';
import { syncHistoryWithStore } from 'react-router-redux';
import { Provider } from 'react-redux';
import { trigger } from 'redial';
// Our deps
import configureStore from './state/store';
import Html from './components/Html';
import getRoutes from './scenes';

const debug = require('debug')('boldr:server');

const port = parseInt(process.env.SSR_PORT, 10);

const app = new Express();
const server = http.createServer(app);
app.use(compression());
app.use(favicon(path.resolve(process.cwd(), './static/favicon.ico')));
app.use(Express.static(path.join(__dirname, '..', 'static')));

app.get('*', (req, res) => {
  if (__DEV__) {
    webpackIsomorphicTools.refresh();
  }

  const memoryHistory = createMemoryHistory(req.originalUrl);
  const location = memoryHistory.createLocation(req.originalUrl);
  const store = configureStore(memoryHistory);
  const history = syncHistoryWithStore(memoryHistory, store);

  function hydrateOnClient() {
    res.send(`
      ${ReactDOM.renderToString()} `);
github Autodesk-Forge / forge-rcdb.nodejs / src / server / api / endpoints / dm.js View on Github external
module.exports = function() {

  const uploadSvc = ServiceManager.getService('UploadSvc')

  /////////////////////////////////////////////////////////
  //
  //
  /////////////////////////////////////////////////////////
  const router = express.Router()

  const shouldCompress = (req, res) => {
    return true
  }

  router.use(compression({
    filter: shouldCompress
  }))

  /////////////////////////////////////////////////////////
  // GET /hubs
  // Get all hubs
  //
  /////////////////////////////////////////////////////////
  router.get('/hubs', async (req, res) => {

    try {

      const forgeSvc = ServiceManager.getService('ForgeSvc')

      const token = await forgeSvc.get3LeggedTokenMaster(req.session)
github malbernaz / preact-hn / src / server.js View on Github external
import compression from "compression";
import express from "express";
import render from "preact-render-to-string";
import serveFavicon from "serve-favicon";
import LRU from "lru-cache";

import assets from "./assets";
import Html from "./components/Html";
import Provider from "./lib/ContextProvider";
import store from "./store";
import routes from "./routes";

const app = express();
const server = http.createServer(app);

app.use(compression({ threshold: 0 }));
app.use(serveFavicon(resolve(__dirname, "public", "favicon.ico")));
app.use(
  express.static(resolve(__dirname, "public"), {
    setHeaders(res) {
      res.setHeader("Cache-Control", "public,max-age=31536000,immutable");
    }
  })
);

const chunks = Object.keys(assets)
  .filter(c => !!assets[c].js && !(/service/i.test(c) || /fetch/.test(c) || /thread/.test(c)))
  .map(c => assets[c].js);

const router = new Router(routes);

function redirect(to, status) {
github Armour / express-webpack-react-redux-typescript-boilerplate / backend / server.js View on Github external
const app = express();
const isProduction = process.env.NODE_ENV === 'production';
const port = process.env.PORT || config.http_port;
const RedisStore = connectRedis(session);
const server = require('http').createServer(app);

if (isProduction) {
  app.use(helmet());
  app.disable('x-powered-by');
  app.use(logger('combined'));
  app.set('trust proxy', 1);
} else {
  app.use(logger('dev'));
}

app.use(compression());
app.use(bodyParser.json({
  limit: '20mb',
}));
app.use(bodyParser.urlencoded({
  limit: '20mb',
  extended: true,
}));
app.use(cookieParser());
app.use(session({
  store: new RedisStore({
    host: isProduction ? config.redis_hostname_prod : config.redis_hostname_dev,
    port: config.redis_port,
  }),
  secret: 'keyboard cat',
  saveUninitialized: false,
  resave: false,
github kiwicom / margarita / apps / graphql / src / server.js View on Github external
return {
      clientIP: requestIp.getClientIp(req),
      ...createContext({ acceptLanguageHeaders }),
    };
  },
  playground: {
    endpoint: playgroundEndpoint,
    settings: {
      'editor.theme': 'light',
    },
  },
  introspection: true,
});

const app = express();
app.use(compression({ threshold: 0 }));
app.use(cors());

if (isDevelopment) {
  app.use(morgan('dev'));
}

server.applyMiddleware({ app });

const handler = serverless(app);
export { handler };

compression

Node.js compression middleware

MIT
Latest version published 5 years ago

Package Health Score

73 / 100
Full package analysis

Popular compression functions