This repository was archived by the owner on Nov 22, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (55 loc) · 1.77 KB
/
index.js
File metadata and controls
90 lines (55 loc) · 1.77 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
83
84
85
86
87
88
89
90
const path = require('path');
const fs = require('fs-extra'); // Using `fs-extra` we can utilize `async` and `await`.
const BasicNodeModule = (function() {
const html = (__dirname + '/temp.html');
const defaults = {
red: 'red',
green: 'green',
orange: 'orange',
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
class BasicNodeModule {
// Singleton pattern:
constructor(options = {}) {
if ( ! BasicNodeModule.instance) {
BasicNodeModule.instance = this;
}
// Save initial options:
this.options = options;
return BasicNodeModule.instance;
}
static init(options = {}) {
const instance = new BasicNodeModule();
// Create a new shallow copy using Object Spread Params (last one in wins):
instance.options = {
...defaults,
...instance.options,
...options,
};
return instance;
}
async run() {
// console.log('options:', this.options);
if (this.options.orange == 'orange') {
// Instead of using `writeFile().then()`, use await:
await fs.writeFile(html, 'Hello world!', 'utf8');
let result = await fs.readFile(html, 'utf8');
await fs.unlink(html);
// Resolve this async function with the result:
return result;
} else {
throw new Error(`Orange isn’t orange, it’s ${this.options.orange}!`);
}
}
}
return BasicNodeModule;
}());
// These options come from `require()({ … options … })` syntax:
module.exports = (options = {}) => {
// If passed, instanciate class and pass options:
if (Object.entries(options).length) {
new BasicNodeModule(options);
}
// Return the `init` method:
return BasicNodeModule.init
};