forked from tradingview/lightweight-charts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve-local-files.js
executable file
·82 lines (67 loc) · 2.02 KB
/
serve-local-files.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const express = require('express');
function serveLocalFiles(filesToServe, port, hostname) {
if (filesToServe.size === 0) {
return Promise.resolve(null);
}
if (Array.from(filesToServe.values()).some(p => !fs.existsSync(p))) {
return Promise.reject('Some of files does not exist');
}
const app = express();
app.get('/:filename', (req, res) => {
const requestedFile = filesToServe.get(req.params.filename);
if (requestedFile === undefined) {
res.sendStatus(404);
} else {
res.sendFile(requestedFile);
}
});
return new Promise(resolve => {
console.log(`Running a server on ${hostname}:${port} to serve ${filesToServe.size} local file(s)`);
const server = app.listen(port, hostname, () => {
resolve(() => {
console.log('Stopping server...');
server.close();
});
});
});
}
module.exports.serveLocalFiles = serveLocalFiles;
function main() {
if (process.argv.length < 3) {
console.log(`Usage: ${process.argv[1]} [...paths]`);
console.log(`Example: ${process.argv[1]} path/to/file renamed-file-name:path/to/file`);
process.exit(1);
}
const portStr = process.env.SERVE_PORT;
const port = portStr ? parseInt(portStr) : 34567;
if (Number.isNaN(port)) {
return Promise.reject(`Port must be a number, given ${portStr}`);
}
const filesToServe = new Map();
for (let i = 2; i < process.argv.length; ++i) {
let servedName;
let filePath;
const parts = process.argv[i].split(':');
if (parts.length === 1) {
filePath = parts[0];
servedName = path.basename(filePath);
} else {
servedName = path.basename(parts[0]);
filePath = parts[1];
}
if (filesToServe.has(servedName)) {
return Promise.reject(`Multiple files with the same name "${servedName}" detected. Use renaming.`);
}
filesToServe.set(servedName, path.resolve(filePath));
}
return serveLocalFiles(filesToServe, port, '0.0.0.0');
}
if (require.main === module) {
main().catch(e => {
console.error('Error:', e);
process.exitCode = 1;
});
}