forked from sindresorhus/electron-serve
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (65 loc) · 2.21 KB
/
index.js
File metadata and controls
82 lines (65 loc) · 2.21 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
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const electron = require('electron');
const stat = promisify(fs.stat);
const getPath = async path_ => {
try {
const result = await stat(path_);
if (result.isFile()) {
return path_;
}
if (result.isDirectory()) {
return getPath(path.join(path_, 'index.html'));
}
} catch (_) {}
};
module.exports = options => {
options = Object.assign({
scheme: 'app'
}, options);
// TODO: Make directory relative to app root. Document it.
if (!options.directory) {
throw new Error('The `directory` option is required');
}
console.log('Options directory: ', options.directory);
options.directory = path.resolve(electron.app.getAppPath(), options.directory);
console.log('Options directory: ', options.directory);
const handler = async(request, callback) => {
console.log('File sent', new URL(request.url).pathname);
const indexPath = path.join(options.directory, 'index.html');
const filePath = path.join(options.directory, decodeURIComponent(new URL(request.url).pathname));
console.log('File Path', getPath(filePath));
callback({
path: (await getPath(filePath)) || indexPath
});
};
if (electron.protocol.registerStandardSchemes) {
// Electron <=4
electron.protocol.registerStandardSchemes([options.scheme], { secure: true });
} else {
// Electron >=5
electron.protocol.registerSchemesAsPrivileged([{
scheme: options.scheme,
privileges: {
secure: true,
standard: true
}
}]);
}
(async() => {
await electron.app.whenReady();
const session = options.partition ?
electron.session.fromPartition(options.partition) :
electron.session.defaultSession;
session.protocol.registerFileProtocol(options.scheme, handler, error => {
if (error) {
throw error;
}
});
})();
return async win => {
await win.loadURL(`${options.scheme}://-`);
};
};