CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-live-server

A development HTTP server with automatic live reload functionality for front-end web development

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

nodejs-api.mddocs/

Node.js API

Programmatic interface for integrating Live Server functionality into build tools, development environments, and custom applications.

Capabilities

Start Server

Start a Live Server instance with custom configuration.

/**
 * Start a live server with the given options
 * @param options - Configuration object (optional)
 * @returns HTTP or HTTPS server instance
 */
liveServer.start(options?: LiveServerOptions): http.Server | https.Server;

Usage Examples:

const liveServer = require("live-server");

// Start with defaults (port 8080, current directory)
const server = liveServer.start();

// Start with custom configuration
const server = liveServer.start({
  port: 3000,
  host: "localhost",
  root: "./dist",
  open: false,
  logLevel: 1
});

// Start HTTPS server
const fs = require("fs");
const httpsServer = liveServer.start({
  port: 8443,
  https: {
    cert: fs.readFileSync("./cert.pem"),
    key: fs.readFileSync("./key.pem")
  }
});

Stop Server

Stop the Live Server and clean up resources.

/**
 * Stop the live server and close file watchers
 * @returns void
 */
liveServer.shutdown(): void;

Usage Examples:

// Start server
liveServer.start({ port: 3000 });

// Stop after some time
setTimeout(() => {
  liveServer.shutdown();
}, 60000);

// Stop on process signals
process.on('SIGINT', () => {
  liveServer.shutdown();
  process.exit();
});

LiveServer Object Properties

Access Live Server instance properties for monitoring and control.

// Live Server singleton object properties
liveServer.server: http.Server | https.Server | null;  // Current server instance
liveServer.watcher: object | null;                   // Chokidar file watcher instance
liveServer.logLevel: number;                            // Current log level

Usage Examples:

// Check if server is running
if (liveServer.server) {
  console.log('Server is running on port:', liveServer.server.address().port);
}

// Access watcher for additional file events
if (liveServer.watcher) {
  liveServer.watcher.on('add', (path) => {
    console.log('File added:', path);
  });
}

// Change log level after startup
liveServer.logLevel = 3; // Enable verbose logging

Configuration Options

Basic Server Options

Core server configuration options.

interface BasicServerOptions {
  host?: string;           // Address to bind to (default: '0.0.0.0')
  port?: number;           // Port number (default: 8080, 0 for random)
  root?: string;           // Root directory to serve (default: process.cwd())
  logLevel?: number;       // Logging verbosity: 0=errors, 1=some, 2=lots (default: 2)
}

Usage Examples:

// Local development setup
liveServer.start({
  host: 'localhost',
  port: 3000,
  root: './src',
  logLevel: 1
});

// Production-like testing
liveServer.start({
  host: '0.0.0.0',
  port: 8080,
  root: './dist',
  logLevel: 0  // Errors only
});

Browser Control Options

Configure automatic browser launching behavior.

interface BrowserOptions {
  open?: string | string[] | boolean;  // Browser launch configuration
  browser?: string;                    // Browser executable to use
  noBrowser?: boolean;                 // DEPRECATED: use open: false
}

Usage Examples:

// Don't open browser
liveServer.start({ open: false });

// Open specific path
liveServer.start({ open: '/dashboard' });

// Open multiple paths
liveServer.start({ open: ['/admin', '/dashboard'] });

// Use specific browser
liveServer.start({ 
  open: true,
  browser: 'firefox'
});

// Legacy option (deprecated)
liveServer.start({ noBrowser: true }); // Use open: false instead

File Watching Options

Configure file system monitoring and live reload behavior.

interface WatchingOptions {
  watch?: string[];        // Paths to exclusively watch for changes
  ignore?: string[];       // Paths to ignore when watching
  ignorePattern?: RegExp;  // Pattern to ignore files (DEPRECATED)
  wait?: number;           // Milliseconds to wait before reloading (default: 100)
  noCssInject?: boolean;   // Disable CSS injection, reload page instead
}

Usage Examples:

// Watch specific directories only
liveServer.start({
  watch: ['./src', './public'],
  ignore: ['node_modules', '*.log']
});

// Ignore specific patterns (deprecated - use ignore array)
liveServer.start({
  ignorePattern: /\.(tmp|log)$/
});

// Reduce reload frequency for slow builds
liveServer.start({
  wait: 1000  // Wait 1 second after changes
});

// Disable CSS injection
liveServer.start({
  noCssInject: true  // Always reload page, even for CSS
});

Single Page Application Options

Configure SPA-specific features and routing.

interface SPAOptions {
  spa?: boolean;           // Enable SPA mode (redirect routes to hash URLs)  
  file?: string;           // Entry point file for SPA fallback routing
}

Usage Examples:

// Basic SPA support
liveServer.start({
  spa: true,
  file: 'index.html'
});

// Serve app from subdirectory
liveServer.start({
  root: './dist',
  file: 'app.html',
  spa: true
});

Security and HTTPS Options

Configure HTTPS and authentication features.

interface SecurityOptions {
  https?: string | object; // HTTPS configuration module path or config object
  httpsModule?: string;    // Custom HTTPS module name (e.g., 'spdy')
  htpasswd?: string;       // Path to htpasswd file for HTTP Basic Auth
  cors?: boolean;          // Enable CORS for any origin
}

Usage Examples:

const fs = require("fs");

// HTTPS with configuration object
liveServer.start({
  https: {
    cert: fs.readFileSync('./server.cert'),
    key: fs.readFileSync('./server.key'),
    passphrase: 'secret'
  }
});

// HTTPS with configuration file
liveServer.start({
  https: './ssl-config.js'
});

// HTTP/2 with spdy module
liveServer.start({
  https: './ssl-config.js',
  httpsModule: 'spdy'
});

// Basic authentication
liveServer.start({
  htpasswd: './users.htpasswd'
});

// Enable CORS
liveServer.start({
  cors: true
});

Middleware and Routing Options

Configure middleware stack and advanced routing.

interface MiddlewareOptions {
  middleware?: (string | Function)[]; // Connect-compatible middleware functions
  mount?: [string, string][];         // Directory mount points: [route, path]
  proxy?: [string, string][];         // Proxy configurations: [route, target]
}

Usage Examples:

// Custom middleware functions
liveServer.start({
  middleware: [
    function(req, res, next) {
      res.setHeader('X-Custom', 'live-server');
      next();
    },
    './path/to/middleware.js'  // Path to middleware file
  ]
});

// Built-in middleware by name
liveServer.start({
  middleware: ['spa', 'cors']
});

// Directory mounting
liveServer.start({
  mount: [
    ['/components', './node_modules'],
    ['/assets', './static']
  ]
});

// API proxying
liveServer.start({
  proxy: [
    ['/api', 'http://localhost:3001'],
    ['/graphql', 'https://api.example.com']
  ]
});

// Complete middleware setup
liveServer.start({
  middleware: [
    function(req, res, next) {
      console.log(`${req.method} ${req.url}`);
      next();
    }
  ],
  mount: [['/vendor', './lib']],
  proxy: [['/api', 'http://localhost:8000']],
  cors: true
});

Complete Configuration Interface

Full TypeScript interface for all available options:

interface LiveServerOptions {
  // Basic server options
  host?: string;                        // Bind address (default: '0.0.0.0')
  port?: number;                        // Port number (default: 8080)
  root?: string;                        // Root directory (default: cwd)
  logLevel?: number;                    // Log level 0-3 (default: 2)
  
  // Browser control
  open?: string | string[] | boolean;   // Browser launch config
  browser?: string;                     // Browser to use
  noBrowser?: boolean;                  // DEPRECATED: use open: false
  
  // File watching
  watch?: string[];                     // Paths to watch exclusively
  ignore?: string[];                    // Paths to ignore
  ignorePattern?: RegExp;               // Ignore pattern (DEPRECATED)
  wait?: number;                        // Reload delay ms (default: 100)
  noCssInject?: boolean;                // Disable CSS injection
  
  // SPA support
  spa?: boolean;                        // Enable SPA mode
  file?: string;                        // Entry file for 404s
  
  // Security
  https?: string | object;              // HTTPS configuration
  httpsModule?: string;                 // Custom HTTPS module
  htpasswd?: string;                    // Basic auth htpasswd file
  cors?: boolean;                       // Enable CORS
  
  // Advanced routing
  middleware?: (string | Function)[];   // Custom middleware
  mount?: [string, string][];           // Mount points
  proxy?: [string, string][];           // Proxy rules
}

Integration Examples

Common integration patterns for build tools and development workflows:

Webpack Development Setup

const liveServer = require("live-server");
const webpack = require("webpack");

// Start Live Server alongside Webpack
const compiler = webpack(webpackConfig);
compiler.watch({}, (err, stats) => {
  if (!err && !stats.hasErrors()) {
    console.log('Build completed, live server will reload...');
  }
});

liveServer.start({
  port: 3000,
  root: './dist',
  wait: 500,  // Wait for webpack to finish writing
  logLevel: 1
});

Gulp Task Integration

const gulp = require("gulp");
const liveServer = require("live-server");

gulp.task('serve', () => {
  liveServer.start({
    port: 8080,
    root: './build',
    middleware: ['./gulp-middleware.js']
  });
});

gulp.task('serve:stop', (cb) => {
  liveServer.shutdown();
  cb();
});

Express Application Proxy

const express = require("express");
const liveServer = require("live-server");

// Start your Express API
const app = express();
app.listen(3001, () => {
  console.log('API server running on port 3001');
  
  // Start Live Server with API proxy
  liveServer.start({
    port: 3000,
    root: './client/build',
    proxy: [['/api', 'http://localhost:3001']],
    spa: true,
    file: 'index.html'
  });
});

Testing Environment Setup

const liveServer = require("live-server");

// Start server for testing
function startTestServer() {
  return new Promise((resolve) => {
    const server = liveServer.start({
      port: 0,  // Random port
      root: './test-fixtures',
      open: false,
      logLevel: 0
    });
    
    server.on('listening', () => {
      const port = server.address().port;
      resolve(`http://localhost:${port}`);
    });
  });
}

// Use in tests
startTestServer().then(baseURL => {
  // Run tests against baseURL
  console.log('Test server started at:', baseURL);
});

docs

cli.md

index.md

nodejs-api.md

tile.json