or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mdcore-server.mdindex.md

core-server.mddocs/

0

# Core Server Function

1

2

The main st() factory function and Mount class provide the core static file serving functionality with multiple configuration options and request handling capabilities.

3

4

## Capabilities

5

6

### st Factory Function

7

8

Creates a configured request handler function for serving static files.

9

10

```javascript { .api }

11

/**

12

* Creates a static file server handler

13

* @param path - Filesystem path to serve files from (required)

14

* @returns Request handler function

15

*/

16

function st(path: string): RequestHandler;

17

18

/**

19

* Creates a static file server handler with URL mount point

20

* @param path - Filesystem path to serve files from (required)

21

* @param url - URL mount point (default: '/')

22

* @returns Request handler function

23

*/

24

function st(path: string, url: string): RequestHandler;

25

26

/**

27

* Creates a static file server handler with full options

28

* @param path - Filesystem path to serve files from (required)

29

* @param url - URL mount point (default: '/')

30

* @param options - Configuration options

31

* @returns Request handler function

32

*/

33

function st(path: string, url: string, options: StOptions): RequestHandler;

34

35

/**

36

* Creates a static file server handler from options object

37

* @param options - Configuration options including path

38

* @returns Request handler function

39

*/

40

function st(options: StOptions): RequestHandler;

41

42

interface RequestHandler {

43

/** Request handler function - returns true if request was handled */

44

(req: http.IncomingMessage, res: http.ServerResponse, next?: Function): boolean;

45

/** Access to underlying Mount instance */

46

_this: Mount;

47

}

48

```

49

50

**Usage Examples:**

51

52

```javascript

53

const st = require('st');

54

const http = require('http');

55

56

// Simple path-only usage

57

const handler1 = st('./public');

58

59

// With URL mount point

60

const handler2 = st('./static', '/static');

61

62

// With full options

63

const handler3 = st('./assets', '/assets', {

64

cache: true,

65

gzip: true,

66

cors: true

67

});

68

69

// Options object approach

70

const handler4 = st({

71

path: './files',

72

url: '/files',

73

index: 'index.html',

74

dot: false

75

});

76

77

// Using with HTTP server

78

http.createServer((req, res) => {

79

if (handler4(req, res)) {

80

return; // st handled the request

81

}

82

res.statusCode = 404;

83

res.end('Not Found');

84

}).listen(3000);

85

86

// Using with Express-style middleware

87

http.createServer((req, res) => {

88

handler4(req, res, () => {

89

res.end('Not a static file');

90

});

91

}).listen(3001);

92

```

93

94

### Mount Class

95

96

Internal Mount class that handles the actual file serving logic. Exposed for advanced usage scenarios.

97

98

```javascript { .api }

99

/**

100

* Mount class constructor - creates a new mount instance

101

* @param options - Configuration options (must include path)

102

* @throws Error if no options provided or invalid options

103

*/

104

class Mount {

105

constructor(options: StOptions);

106

}

107

```

108

109

**Usage Example:**

110

111

```javascript

112

const { Mount } = require('st');

113

114

const mount = new Mount({

115

path: './public',

116

url: '/public',

117

cache: true

118

});

119

120

// Access mount properties

121

console.log(mount.path); // Resolved filesystem path

122

console.log(mount.url); // URL mount point

123

console.log(mount.opt); // Original options

124

```

125

126

### Request Handler Method

127

128

The main request handling method of the Mount class.

129

130

```javascript { .api }

131

/**

132

* Handles HTTP requests for static files

133

* @param req - HTTP request object

134

* @param res - HTTP response object

135

* @param next - Optional callback for unhandled requests (Express-style)

136

* @returns true if request was handled, false otherwise

137

*/

138

serve(req: http.IncomingMessage, res: http.ServerResponse, next?: Function): boolean;

139

```

140

141

**Usage Example:**

142

143

```javascript

144

const mount = new Mount({ path: './static' });

145

146

http.createServer((req, res) => {

147

const handled = mount.serve(req, res, () => {

148

res.statusCode = 404;

149

res.end('Not found');

150

});

151

152

if (!handled) {

153

console.log('Request not handled by st');

154

}

155

}).listen(3000);

156

```

157

158

### Path and URL Utilities

159

160

Utility methods for converting between filesystem paths and URLs.

161

162

```javascript { .api }

163

/**

164

* Extracts path component from URI with security checks

165

* @param url - Request URL to process

166

* @returns Processed path string, 403 for forbidden paths, or false for invalid URLs

167

*/

168

getUriPath(url: string): string | number | false;

169

170

/**

171

* Converts URL path to filesystem path

172

* @param uriPath - URI path component (from getUriPath)

173

* @returns Absolute filesystem path

174

*/

175

getPath(uriPath: string): string;

176

177

/**

178

* Converts filesystem path to URL

179

* @param filePath - Absolute filesystem path

180

* @returns URL path or false if path is outside served directory

181

*/

182

getUrl(filePath: string): string | false;

183

```

184

185

**Usage Example:**

186

187

```javascript

188

const mount = new Mount({ path: '/var/www', url: '/static' });

189

190

// Extract and validate URI path

191

const uriPath = mount.getUriPath('/static/images/logo.png');

192

if (uriPath === 403) {

193

console.log('Security violation detected');

194

} else if (uriPath === false) {

195

console.log('Invalid URL');

196

} else {

197

// Convert to filesystem path

198

const fsPath = mount.getPath(uriPath);

199

console.log(fsPath); // '/var/www/images/logo.png'

200

201

// Convert back to URL

202

const url = mount.getUrl(fsPath);

203

console.log(url); // '/static/images/logo.png'

204

}

205

```

206

207

### Error Handling

208

209

Built-in error handling with appropriate HTTP status codes.

210

211

```javascript { .api }

212

/**

213

* Handles errors and sends appropriate HTTP responses

214

* @param error - Error object or HTTP status code number

215

* @param res - HTTP response object

216

*/

217

error(error: Error | number, res: http.ServerResponse): void;

218

```

219

220

**Error Codes:**

221

- `404`: File not found (ENOENT, EISDIR errors)

222

- `403`: Forbidden (EPERM, EACCES errors, dot files, path traversal)

223

- `500`: Server error (other errors)

224

225

### Directory Handling

226

227

Methods for handling directory requests and auto-indexing.

228

229

```javascript { .api }

230

/**

231

* Handles directory requests - serves index file or generates directory listing

232

* @param path - Filesystem directory path

233

* @param req - HTTP request object

234

* @param res - HTTP response object

235

*/

236

index(path: string, req: http.IncomingMessage, res: http.ServerResponse): void;

237

238

/**

239

* Generates HTML directory listing

240

* @param path - Filesystem directory path

241

* @param req - HTTP request object

242

* @param res - HTTP response object

243

*/

244

autoindex(path: string, req: http.IncomingMessage, res: http.ServerResponse): void;

245

```

246

247

### File Serving

248

249

Methods for serving individual files with caching and compression.

250

251

```javascript { .api }

252

/**

253

* Serves individual files - determines whether to use cache or streaming

254

* @param path - Filesystem file path

255

* @param fd - File descriptor

256

* @param stat - File stats object

257

* @param etag - Generated ETag for the file

258

* @param req - HTTP request object

259

* @param res - HTTP response object

260

* @param end - Cleanup function for file descriptor

261

*/

262

file(path: string, fd: number, stat: fs.Stats, etag: string, req: http.IncomingMessage, res: http.ServerResponse, end: Function): void;

263

264

/**

265

* Serves files from memory cache

266

* @param path - Filesystem file path

267

* @param stat - File stats object

268

* @param etag - Generated ETag for the file

269

* @param req - HTTP request object

270

* @param res - HTTP response object

271

*/

272

cachedFile(path: string, stat: fs.Stats, etag: string, req: http.IncomingMessage, res: http.ServerResponse): void;

273

274

/**

275

* Streams files from filesystem with optional compression and caching

276

* @param path - Filesystem file path

277

* @param fd - File descriptor

278

* @param stat - File stats object

279

* @param etag - Generated ETag for the file

280

* @param req - HTTP request object

281

* @param res - HTTP response object

282

* @param end - Cleanup function for file descriptor

283

*/

284

streamFile(path: string, fd: number, stat: fs.Stats, etag: string, req: http.IncomingMessage, res: http.ServerResponse, end: Function): void;

285

```

286

287

### Cache Loading Methods

288

289

Internal methods used by the caching system to load data into various caches.

290

291

```javascript { .api }

292

/**

293

* Loads file statistics into the stat cache

294

* @param key - Cache key (either 'fd:path' or just path)

295

* @param callback - Callback function (err, stat)

296

*/

297

_loadStat(key: string, callback: (err: Error | null, stat?: fs.Stats) => void): void;

298

299

/**

300

* Loads directory index HTML into the index cache

301

* @param path - Directory filesystem path

302

* @param callback - Callback function (err, html)

303

*/

304

_loadIndex(path: string, callback: (err: Error | null, html?: Buffer) => void): void;

305

306

/**

307

* Loads directory listing into the readdir cache

308

* @param path - Directory filesystem path

309

* @param callback - Callback function (err, data)

310

*/

311

_loadReaddir(path: string, callback: (err: Error | null, data?: object) => void): void;

312

313

/**

314

* Content loading method - should never be called as content is loaded via streaming

315

* @param key - Cache key (unused)

316

* @param callback - Callback function that returns an error

317

*/

318

_loadContent(key: string, callback: (err: Error) => void): void;

319

```

320

321

### Utility Functions

322

323

Static utility functions used internally by the st module.

324

325

```javascript { .api }

326

/**

327

* Generates ETag from file stats

328

* @param stat - File stats object

329

* @returns ETag string in format "dev-ino-mtime"

330

*/

331

function getEtag(stat: fs.Stats): string;

332

333

/**

334

* Determines if gzip compression should be used for a request

335

* @param path - File path

336

* @param req - HTTP request object

337

* @returns true if gzip should be used

338

*/

339

function getGz(path: string, req: http.IncomingMessage): boolean;

340

```