Skip to content

Commit ee2ba72

Browse files
committed
Global state with modules singleton example
1 parent b6bb5e6 commit ee2ba72

File tree

4 files changed

+55
-0
lines changed

4 files changed

+55
-0
lines changed

NodeJS/0-global-state/main.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
const state = require('./state.js');
4+
const unit1 = require('./unit1.js');
5+
const unit2 = require('./unit2.js');
6+
7+
const INITIAL_STATE = {
8+
time: Date.now(),
9+
counter: 0,
10+
};
11+
12+
unit1.restore(INITIAL_STATE);
13+
14+
setInterval(() => {
15+
state.counter++;
16+
unit2.show();
17+
unit1.save();
18+
}, 1000);

NodeJS/0-global-state/state.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
'use strict';
2+
3+
const state = {};
4+
5+
module.exports = state;

NodeJS/0-global-state/unit1.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
'use strict';
2+
3+
const fs = require('node:fs').promises;
4+
const state = require('./state.js');
5+
6+
const fileName = './state.json';
7+
8+
const save = async () => {
9+
const data = JSON.stringify(state);
10+
await fs.writeFile(fileName, data);
11+
};
12+
13+
const restore = async (initialState) => {
14+
try {
15+
const data = await fs.readFile(fileName);
16+
const stored = JSON.parse(data);
17+
Object.assign(state, stored);
18+
} catch {
19+
Object.assign(state, initialState);
20+
}
21+
};
22+
23+
module.exports = { save, restore };

NodeJS/0-global-state/unit2.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
'use strict';
2+
3+
const state = require('./state.js');
4+
5+
const show = () => {
6+
console.table(state);
7+
};
8+
9+
module.exports = { show };

0 commit comments

Comments
 (0)