or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Node HTTP Server

1

2

Node HTTP Server is a lightweight, zero-dependency HTTP/HTTPS server for Node.js that provides both programmatic API and CLI functionality. It features configurable server settings, HTTPS support, multiple domain handling, proxy capabilities, template processing through lifecycle hooks, and extensible server architecture.

3

4

## Package Information

5

6

- **Package Name**: node-http-server

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install node-http-server`

10

11

## Core Imports

12

13

```javascript

14

const server = require('node-http-server');

15

```

16

17

The package exports a pre-instantiated Server instance for immediate use, plus access to the Server class and Config class for creating custom instances.

18

19

## Basic Usage

20

21

```javascript

22

const server = require('node-http-server');

23

24

// Simple server deployment

25

server.deploy({

26

port: 8000,

27

root: './public',

28

verbose: true

29

});

30

31

// With ready callback

32

server.deploy({

33

port: 3000,

34

root: __dirname + '/app'

35

}, function(server) {

36

console.log(`Server running on port ${server.config.port}`);

37

});

38

```

39

40

## Architecture

41

42

Node HTTP Server is built around several key components:

43

44

- **Server Class**: Main server class providing HTTP/HTTPS functionality with lifecycle hooks

45

- **Config Class**: Configuration management with sensible defaults and validation

46

- **Lifecycle Hooks**: Extensible request/response processing pipeline (onRawRequest, onRequest, beforeServe, afterServe)

47

- **Static File Serving**: Built-in file serving with MIME type detection and caching control

48

- **Multi-Protocol Support**: HTTP and HTTPS with automatic certificate handling

49

- **Multi-Domain Support**: Virtual host capabilities with domain-specific document roots

50

51

## Capabilities

52

53

### Server Deployment

54

55

Deploy HTTP and/or HTTPS servers with comprehensive configuration options.

56

57

```javascript { .api }

58

/**

59

* Deploy server with configuration

60

* @param {Object} userConfig - Configuration object to merge with defaults

61

* @param {Function} readyCallback - Called when server starts

62

*/

63

server.deploy(userConfig, readyCallback);

64

65

/**

66

* Server class for creating custom instances

67

* @param {Object} userConfig - Configuration object to merge with defaults

68

*/

69

const Server = server.Server;

70

const myServer = new Server(userConfig);

71

```

72

73

**Usage Examples:**

74

75

```javascript

76

const server = require('node-http-server');

77

78

// Basic HTTP server

79

server.deploy({

80

port: 8080,

81

root: './public'

82

});

83

84

// HTTPS server

85

server.deploy({

86

port: 8000,

87

https: {

88

privateKey: '/path/to/private.key',

89

certificate: '/path/to/certificate.crt',

90

port: 443

91

}

92

});

93

94

// Multiple servers

95

const Server = server.Server;

96

const server1 = new Server({ port: 8000 });

97

const server2 = new Server({ port: 9000 });

98

99

server1.deploy();

100

server2.deploy();

101

```

102

103

### Request Lifecycle Hooks

104

105

Extensible hooks for customizing request processing pipeline.

106

107

```javascript { .api }

108

/**

109

* Raw request hook - called before any processing

110

* @param {http.IncomingMessage} request - Raw HTTP request

111

* @param {http.ServerResponse} response - HTTP response object

112

* @param {Function} serve - Serve function reference

113

* @returns {boolean|void} - Return truthy to bypass normal processing

114

*/

115

server.onRawRequest = function(request, response, serve) {};

116

117

/**

118

* Request hook - called after request decoration

119

* @param {Object} request - Decorated request with uri, query properties

120

* @param {http.ServerResponse} response - HTTP response object

121

* @param {Function} serve - Serve function reference

122

* @returns {boolean|void} - Return truthy to bypass normal processing

123

*/

124

server.onRequest = function(request, response, serve) {};

125

126

/**

127

* Before serve hook - called before serving response, allows body modification

128

* @param {Object} request - Decorated request object

129

* @param {http.ServerResponse} response - HTTP response object

130

* @param {RefString} body - Response body as RefString for modification

131

* @param {RefString} encoding - Response encoding as RefString for modification

132

* @param {Function} serve - Serve function reference

133

* @returns {boolean|void} - Return truthy to handle serving manually

134

*/

135

server.beforeServe = function(request, response, body, encoding, serve) {};

136

137

/**

138

* After serve hook - called after response is sent

139

* @param {Object} request - Decorated request object

140

*/

141

server.afterServe = function(request) {};

142

```

143

144

**Usage Examples:**

145

146

```javascript

147

const server = require('node-http-server');

148

149

// API endpoint handling

150

server.onRequest = function(request, response, serve) {

151

if (request.uri.pathname.startsWith('/api/')) {

152

const data = { message: 'Hello from API', path: request.uri.pathname };

153

serve(request, response, JSON.stringify(data));

154

response.setHeader('Content-Type', 'application/json');

155

return true; // Skip file serving

156

}

157

return false; // Continue normal processing

158

};

159

160

// Template processing

161

server.beforeServe = function(request, response, body, encoding) {

162

if (response.getHeader('Content-Type') === 'text/html') {

163

const timestamp = new Date().toISOString();

164

body.value = body.value.replace('{{timestamp}}', timestamp);

165

}

166

};

167

168

// Request logging

169

server.afterServe = function(request) {

170

console.log(`Served: ${request.uri.pathname} at ${new Date()}`);

171

};

172

173

server.deploy({ port: 8000, root: './public' });

174

```

175

176

### Configuration Management

177

178

Comprehensive configuration system with defaults and validation.

179

180

```javascript { .api }

181

/**

182

* Configuration class with default values

183

* @param {Object} userConfig - Configuration overrides

184

*/

185

const Config = server.Config;

186

const config = new Config(userConfig);

187

188

interface ConfigOptions {

189

/** Enable verbose logging */

190

verbose: boolean;

191

/** HTTP server port */

192

port: number;

193

/** Document root directory */

194

root: string;

195

/** Server domain/hostname */

196

domain: string;

197

/** Enable logging or specify log file path */

198

log: boolean | string;

199

/** Custom logging function */

200

logFunction: Function;

201

/** Multiple domain configuration */

202

domains: Object;

203

/** Server-specific settings */

204

server: {

205

/** Default index file */

206

index: string;

207

/** Disable caching headers */

208

noCache: boolean;

209

/** Server timeout in milliseconds */

210

timeout: number;

211

};

212

/** HTTPS configuration */

213

https: {

214

/** Certificate Authority file path */

215

ca: string;

216

/** Private key file path */

217

privateKey: string;

218

/** Certificate file path */

219

certificate: string;

220

/** Certificate passphrase */

221

passphrase: string | boolean;

222

/** HTTPS port */

223

port: number;

224

/** HTTPS only mode */

225

only: boolean;

226

};

227

/** MIME type mappings */

228

contentType: Object;

229

/** Restricted file types */

230

restrictedType: Object;

231

/** Error page configuration */

232

errors: {

233

headers: Object;

234

404: string;

235

415: string;

236

403: string;

237

500: string;

238

};

239

}

240

```

241

242

**Usage Examples:**

243

244

```javascript

245

const server = require('node-http-server');

246

const Config = server.Config;

247

248

// Custom configuration instance

249

const config = new Config({

250

port: 9000,

251

verbose: true,

252

server: {

253

index: 'home.html',

254

noCache: false

255

}

256

});

257

258

const customServer = new server.Server(config);

259

customServer.deploy();

260

261

// Multiple domains

262

server.deploy({

263

port: 8000,

264

domain: 'localhost',

265

domains: {

266

'api.example.com': '/path/to/api/root',

267

'www.example.com': '/path/to/www/root'

268

}

269

});

270

```

271

272

### HTTPS Support

273

274

Built-in HTTPS server support with certificate handling.

275

276

```javascript { .api }

277

interface HTTPSConfig {

278

/** Certificate Authority file path */

279

ca?: string;

280

/** Private key file path */

281

privateKey: string;

282

/** Certificate file path */

283

certificate: string;

284

/** Certificate passphrase */

285

passphrase?: string | boolean;

286

/** HTTPS port */

287

port?: number;

288

/** HTTPS only mode - disables HTTP server */

289

only?: boolean;

290

}

291

```

292

293

**Usage Examples:**

294

295

```javascript

296

const server = require('node-http-server');

297

298

// HTTPS with HTTP redirect

299

server.deploy({

300

port: 8000,

301

https: {

302

privateKey: './certs/server.key',

303

certificate: './certs/server.crt',

304

port: 8443

305

}

306

});

307

308

// HTTPS only

309

server.deploy({

310

https: {

311

privateKey: './certs/server.key',

312

certificate: './certs/server.crt',

313

port: 443,

314

only: true

315

}

316

});

317

318

// HTTPS with CA and passphrase

319

server.deploy({

320

https: {

321

privateKey: './certs/server.key',

322

certificate: './certs/server.crt',

323

ca: './certs/ca.crt',

324

passphrase: 'mypassword',

325

port: 8443

326

}

327

});

328

```

329

330

### Manual Response Handling

331

332

Direct response serving for custom content delivery.

333

334

```javascript { .api }

335

/**

336

* Manual serve function for custom responses

337

* @param {Object} request - Request object

338

* @param {http.ServerResponse} response - Response object

339

* @param {string} body - Response body content

340

* @param {string} encoding - Response encoding (default: 'utf8')

341

*/

342

server.serve(request, response, body, encoding);

343

344

/**

345

* Manual file serving function

346

* @param {string} filename - File path to serve

347

* @param {boolean} exists - Whether file exists

348

* @param {Object} request - Request object

349

* @param {http.ServerResponse} response - Response object

350

*/

351

server.serveFile(filename, exists, request, response);

352

```

353

354

**Usage Examples:**

355

356

```javascript

357

const server = require('node-http-server');

358

359

server.onRequest = function(request, response, serve) {

360

if (request.uri.pathname === '/status') {

361

response.setHeader('Content-Type', 'application/json');

362

serve(request, response, JSON.stringify({

363

status: 'ok',

364

timestamp: Date.now(),

365

uptime: process.uptime()

366

}));

367

return true;

368

}

369

370

if (request.uri.pathname === '/download') {

371

const filePath = './files/document.pdf';

372

response.setHeader('Content-Type', 'application/pdf');

373

response.setHeader('Content-Disposition', 'attachment; filename="document.pdf"');

374

server.serveFile(filePath, true, request, response);

375

return true;

376

}

377

};

378

379

server.deploy({ port: 8000 });

380

```

381

382

### CLI Usage

383

384

Command-line interface for quick server deployment.

385

386

```bash

387

# Basic usage

388

node-http-server

389

390

# With configuration

391

node-http-server port=3000 verbose=true root=/path/to/files

392

393

# Available CLI options

394

node-http-server port=8080 domain=localhost index=home.html noCache=false verbose=true

395

```

396

397

All Config class properties can be set via CLI arguments using key=value format.

398

399

## Types

400

401

```javascript { .api }

402

/**

403

* Reference string wrapper for pass-by-reference modification

404

*/

405

class RefString {

406

constructor(value?: string);

407

408

/** The wrapped string value */

409

get value(): string;

410

set value(value: string): string;

411

}

412

413

/**

414

* Decorated request object with additional properties

415

*/

416

interface DecoratedRequest extends http.IncomingMessage {

417

/** Parsed URI with protocol, host, pathname, query properties */

418

uri: {

419

protocol: string;

420

host: string;

421

hostname: string;

422

port: number;

423

pathname: string;

424

query: Object;

425

};

426

/** Raw URL path */

427

url: string;

428

/** Document root being used for this request */

429

serverRoot: string;

430

/** Request body content */

431

body: string;

432

}

433

434

/**

435

* Server instance with configuration and lifecycle hooks

436

*/

437

interface ServerInstance {

438

/** Server configuration */

439

config: ConfigOptions;

440

/** HTTP server instance */

441

server?: http.Server;

442

/** HTTPS server instance */

443

secureServer?: https.Server;

444

/** Deploy method */

445

deploy(userConfig?: Object, readyCallback?: Function): void;

446

/** Lifecycle hooks */

447

onRawRequest(request: http.IncomingMessage, response: http.ServerResponse, serve: Function): boolean | void;

448

onRequest(request: DecoratedRequest, response: http.ServerResponse, serve: Function): boolean | void;

449

beforeServe(request: DecoratedRequest, response: http.ServerResponse, body: RefString, encoding: RefString, serve: Function): boolean | void;

450

afterServe(request: DecoratedRequest): void;

451

/** Utility methods */

452

serve(request: DecoratedRequest, response: http.ServerResponse, body: string, encoding?: string): void;

453

serveFile(filename: string, exists: boolean, request: DecoratedRequest, response: http.ServerResponse): void;

454

}

455

```