-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdevelopment-server.js
More file actions
69 lines (62 loc) · 2 KB
/
development-server.js
File metadata and controls
69 lines (62 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const express = require( 'express' );
const fs = require( 'fs' );
const http = require( 'http' );
const morgan = require( 'morgan' );
const util = require( 'util' );
const path = require( 'path' );
const stream = require( 'stream' );
const pipeline = util.promisify( stream.pipeline );
const app = express();
// Use morgan middleware for logging
app.use( morgan( 'combined' ) );
app.get( '/images/fonts/*path', async ( req, res ) => {
// Serve font collections from the local filesystem at the same url paths as s.w.org for both WP and Gutenberg releases:
// e.g. /images/fonts/wp-6.5/... and /images/fonts/17.7/...
const subdir = req.url.includes( '/wp-' ) ? '' : 'gutenberg-';
const pathSegment = req.params.path.join( '/' );
const filePath = path.join( __dirname, 'releases', subdir + pathSegment );
// Rewrite font preview URLs in the collection JSON to use the development server
if ( path.extname( filePath ) === '.json' ) {
const readStream = fs.createReadStream( filePath, {
encoding: 'utf8',
} );
const transformStream = new stream.Transform( {
transform( chunk, encoding, callback ) {
this.push(
chunk
.toString()
.replaceAll(
'https://s.w.org/images/fonts',
'http://localhost:9158/images/fonts'
)
);
callback();
},
} );
readStream.on( 'error', () => {
res.status( 404 ).send( `File not found: ${ filePath }` );
} );
res.setHeader( 'Content-Type', 'application/json' );
try {
await pipeline( readStream, transformStream, res );
} catch ( err ) {
// eslint-disable-next-line no-console
console.error( err );
if ( ! res.headersSent ) {
res.status( 500 ).send(
'An error occurred while processing the file'
);
}
}
} else {
res.sendFile( filePath, ( err ) => {
if ( err ) {
res.status( 404 ).send( `File not found: ${ filePath }` );
}
} );
}
} );
http.createServer( app ).listen( 9158, () => {
// eslint-disable-next-line no-console
console.log( 'HTTP Server running at http://localhost:9158' );
} );