0
# Node.js API
1
2
Programmatic interface for integrating Live Server functionality into build tools, development environments, and custom applications.
3
4
## Capabilities
5
6
### Start Server
7
8
Start a Live Server instance with custom configuration.
9
10
```javascript { .api }
11
/**
12
* Start a live server with the given options
13
* @param options - Configuration object (optional)
14
* @returns HTTP or HTTPS server instance
15
*/
16
liveServer.start(options?: LiveServerOptions): http.Server | https.Server;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const liveServer = require("live-server");
23
24
// Start with defaults (port 8080, current directory)
25
const server = liveServer.start();
26
27
// Start with custom configuration
28
const server = liveServer.start({
29
port: 3000,
30
host: "localhost",
31
root: "./dist",
32
open: false,
33
logLevel: 1
34
});
35
36
// Start HTTPS server
37
const fs = require("fs");
38
const httpsServer = liveServer.start({
39
port: 8443,
40
https: {
41
cert: fs.readFileSync("./cert.pem"),
42
key: fs.readFileSync("./key.pem")
43
}
44
});
45
```
46
47
### Stop Server
48
49
Stop the Live Server and clean up resources.
50
51
```javascript { .api }
52
/**
53
* Stop the live server and close file watchers
54
* @returns void
55
*/
56
liveServer.shutdown(): void;
57
```
58
59
**Usage Examples:**
60
61
```javascript
62
// Start server
63
liveServer.start({ port: 3000 });
64
65
// Stop after some time
66
setTimeout(() => {
67
liveServer.shutdown();
68
}, 60000);
69
70
// Stop on process signals
71
process.on('SIGINT', () => {
72
liveServer.shutdown();
73
process.exit();
74
});
75
```
76
77
### LiveServer Object Properties
78
79
Access Live Server instance properties for monitoring and control.
80
81
```javascript { .api }
82
// Live Server singleton object properties
83
liveServer.server: http.Server | https.Server | null; // Current server instance
84
liveServer.watcher: object | null; // Chokidar file watcher instance
85
liveServer.logLevel: number; // Current log level
86
```
87
88
**Usage Examples:**
89
90
```javascript
91
// Check if server is running
92
if (liveServer.server) {
93
console.log('Server is running on port:', liveServer.server.address().port);
94
}
95
96
// Access watcher for additional file events
97
if (liveServer.watcher) {
98
liveServer.watcher.on('add', (path) => {
99
console.log('File added:', path);
100
});
101
}
102
103
// Change log level after startup
104
liveServer.logLevel = 3; // Enable verbose logging
105
```
106
107
## Configuration Options
108
109
### Basic Server Options
110
111
Core server configuration options.
112
113
```javascript { .api }
114
interface BasicServerOptions {
115
host?: string; // Address to bind to (default: '0.0.0.0')
116
port?: number; // Port number (default: 8080, 0 for random)
117
root?: string; // Root directory to serve (default: process.cwd())
118
logLevel?: number; // Logging verbosity: 0=errors, 1=some, 2=lots (default: 2)
119
}
120
```
121
122
**Usage Examples:**
123
124
```javascript
125
// Local development setup
126
liveServer.start({
127
host: 'localhost',
128
port: 3000,
129
root: './src',
130
logLevel: 1
131
});
132
133
// Production-like testing
134
liveServer.start({
135
host: '0.0.0.0',
136
port: 8080,
137
root: './dist',
138
logLevel: 0 // Errors only
139
});
140
```
141
142
### Browser Control Options
143
144
Configure automatic browser launching behavior.
145
146
```javascript { .api }
147
interface BrowserOptions {
148
open?: string | string[] | boolean; // Browser launch configuration
149
browser?: string; // Browser executable to use
150
noBrowser?: boolean; // DEPRECATED: use open: false
151
}
152
```
153
154
**Usage Examples:**
155
156
```javascript
157
// Don't open browser
158
liveServer.start({ open: false });
159
160
// Open specific path
161
liveServer.start({ open: '/dashboard' });
162
163
// Open multiple paths
164
liveServer.start({ open: ['/admin', '/dashboard'] });
165
166
// Use specific browser
167
liveServer.start({
168
open: true,
169
browser: 'firefox'
170
});
171
172
// Legacy option (deprecated)
173
liveServer.start({ noBrowser: true }); // Use open: false instead
174
```
175
176
### File Watching Options
177
178
Configure file system monitoring and live reload behavior.
179
180
```javascript { .api }
181
interface WatchingOptions {
182
watch?: string[]; // Paths to exclusively watch for changes
183
ignore?: string[]; // Paths to ignore when watching
184
ignorePattern?: RegExp; // Pattern to ignore files (DEPRECATED)
185
wait?: number; // Milliseconds to wait before reloading (default: 100)
186
noCssInject?: boolean; // Disable CSS injection, reload page instead
187
}
188
```
189
190
**Usage Examples:**
191
192
```javascript
193
// Watch specific directories only
194
liveServer.start({
195
watch: ['./src', './public'],
196
ignore: ['node_modules', '*.log']
197
});
198
199
// Ignore specific patterns (deprecated - use ignore array)
200
liveServer.start({
201
ignorePattern: /\.(tmp|log)$/
202
});
203
204
// Reduce reload frequency for slow builds
205
liveServer.start({
206
wait: 1000 // Wait 1 second after changes
207
});
208
209
// Disable CSS injection
210
liveServer.start({
211
noCssInject: true // Always reload page, even for CSS
212
});
213
```
214
215
### Single Page Application Options
216
217
Configure SPA-specific features and routing.
218
219
```javascript { .api }
220
interface SPAOptions {
221
spa?: boolean; // Enable SPA mode (redirect routes to hash URLs)
222
file?: string; // Entry point file for SPA fallback routing
223
}
224
```
225
226
**Usage Examples:**
227
228
```javascript
229
// Basic SPA support
230
liveServer.start({
231
spa: true,
232
file: 'index.html'
233
});
234
235
// Serve app from subdirectory
236
liveServer.start({
237
root: './dist',
238
file: 'app.html',
239
spa: true
240
});
241
```
242
243
### Security and HTTPS Options
244
245
Configure HTTPS and authentication features.
246
247
```javascript { .api }
248
interface SecurityOptions {
249
https?: string | object; // HTTPS configuration module path or config object
250
httpsModule?: string; // Custom HTTPS module name (e.g., 'spdy')
251
htpasswd?: string; // Path to htpasswd file for HTTP Basic Auth
252
cors?: boolean; // Enable CORS for any origin
253
}
254
```
255
256
**Usage Examples:**
257
258
```javascript
259
const fs = require("fs");
260
261
// HTTPS with configuration object
262
liveServer.start({
263
https: {
264
cert: fs.readFileSync('./server.cert'),
265
key: fs.readFileSync('./server.key'),
266
passphrase: 'secret'
267
}
268
});
269
270
// HTTPS with configuration file
271
liveServer.start({
272
https: './ssl-config.js'
273
});
274
275
// HTTP/2 with spdy module
276
liveServer.start({
277
https: './ssl-config.js',
278
httpsModule: 'spdy'
279
});
280
281
// Basic authentication
282
liveServer.start({
283
htpasswd: './users.htpasswd'
284
});
285
286
// Enable CORS
287
liveServer.start({
288
cors: true
289
});
290
```
291
292
### Middleware and Routing Options
293
294
Configure middleware stack and advanced routing.
295
296
```javascript { .api }
297
interface MiddlewareOptions {
298
middleware?: (string | Function)[]; // Connect-compatible middleware functions
299
mount?: [string, string][]; // Directory mount points: [route, path]
300
proxy?: [string, string][]; // Proxy configurations: [route, target]
301
}
302
```
303
304
**Usage Examples:**
305
306
```javascript
307
// Custom middleware functions
308
liveServer.start({
309
middleware: [
310
function(req, res, next) {
311
res.setHeader('X-Custom', 'live-server');
312
next();
313
},
314
'./path/to/middleware.js' // Path to middleware file
315
]
316
});
317
318
// Built-in middleware by name
319
liveServer.start({
320
middleware: ['spa', 'cors']
321
});
322
323
// Directory mounting
324
liveServer.start({
325
mount: [
326
['/components', './node_modules'],
327
['/assets', './static']
328
]
329
});
330
331
// API proxying
332
liveServer.start({
333
proxy: [
334
['/api', 'http://localhost:3001'],
335
['/graphql', 'https://api.example.com']
336
]
337
});
338
339
// Complete middleware setup
340
liveServer.start({
341
middleware: [
342
function(req, res, next) {
343
console.log(`${req.method} ${req.url}`);
344
next();
345
}
346
],
347
mount: [['/vendor', './lib']],
348
proxy: [['/api', 'http://localhost:8000']],
349
cors: true
350
});
351
```
352
353
## Complete Configuration Interface
354
355
Full TypeScript interface for all available options:
356
357
```typescript { .api }
358
interface LiveServerOptions {
359
// Basic server options
360
host?: string; // Bind address (default: '0.0.0.0')
361
port?: number; // Port number (default: 8080)
362
root?: string; // Root directory (default: cwd)
363
logLevel?: number; // Log level 0-3 (default: 2)
364
365
// Browser control
366
open?: string | string[] | boolean; // Browser launch config
367
browser?: string; // Browser to use
368
noBrowser?: boolean; // DEPRECATED: use open: false
369
370
// File watching
371
watch?: string[]; // Paths to watch exclusively
372
ignore?: string[]; // Paths to ignore
373
ignorePattern?: RegExp; // Ignore pattern (DEPRECATED)
374
wait?: number; // Reload delay ms (default: 100)
375
noCssInject?: boolean; // Disable CSS injection
376
377
// SPA support
378
spa?: boolean; // Enable SPA mode
379
file?: string; // Entry file for 404s
380
381
// Security
382
https?: string | object; // HTTPS configuration
383
httpsModule?: string; // Custom HTTPS module
384
htpasswd?: string; // Basic auth htpasswd file
385
cors?: boolean; // Enable CORS
386
387
// Advanced routing
388
middleware?: (string | Function)[]; // Custom middleware
389
mount?: [string, string][]; // Mount points
390
proxy?: [string, string][]; // Proxy rules
391
}
392
```
393
394
## Integration Examples
395
396
Common integration patterns for build tools and development workflows:
397
398
### Webpack Development Setup
399
400
```javascript
401
const liveServer = require("live-server");
402
const webpack = require("webpack");
403
404
// Start Live Server alongside Webpack
405
const compiler = webpack(webpackConfig);
406
compiler.watch({}, (err, stats) => {
407
if (!err && !stats.hasErrors()) {
408
console.log('Build completed, live server will reload...');
409
}
410
});
411
412
liveServer.start({
413
port: 3000,
414
root: './dist',
415
wait: 500, // Wait for webpack to finish writing
416
logLevel: 1
417
});
418
```
419
420
### Gulp Task Integration
421
422
```javascript
423
const gulp = require("gulp");
424
const liveServer = require("live-server");
425
426
gulp.task('serve', () => {
427
liveServer.start({
428
port: 8080,
429
root: './build',
430
middleware: ['./gulp-middleware.js']
431
});
432
});
433
434
gulp.task('serve:stop', (cb) => {
435
liveServer.shutdown();
436
cb();
437
});
438
```
439
440
### Express Application Proxy
441
442
```javascript
443
const express = require("express");
444
const liveServer = require("live-server");
445
446
// Start your Express API
447
const app = express();
448
app.listen(3001, () => {
449
console.log('API server running on port 3001');
450
451
// Start Live Server with API proxy
452
liveServer.start({
453
port: 3000,
454
root: './client/build',
455
proxy: [['/api', 'http://localhost:3001']],
456
spa: true,
457
file: 'index.html'
458
});
459
});
460
```
461
462
### Testing Environment Setup
463
464
```javascript
465
const liveServer = require("live-server");
466
467
// Start server for testing
468
function startTestServer() {
469
return new Promise((resolve) => {
470
const server = liveServer.start({
471
port: 0, // Random port
472
root: './test-fixtures',
473
open: false,
474
logLevel: 0
475
});
476
477
server.on('listening', () => {
478
const port = server.address().port;
479
resolve(`http://localhost:${port}`);
480
});
481
});
482
}
483
484
// Use in tests
485
startTestServer().then(baseURL => {
486
// Run tests against baseURL
487
console.log('Test server started at:', baseURL);
488
});
489
```