Skip to content

Commit 1cf9d41

Browse files
committed
Add closure state example
1 parent f3289f0 commit 1cf9d41

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

NodeJS/2-closure/main.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
'use strict';
2+
3+
const unit1 = require('./unit1.js');
4+
const unit2 = require('./unit2.js');
5+
6+
setTimeout(() => {
7+
unit2();
8+
const res = unit1();
9+
console.log({ res });
10+
}, 100);

NodeJS/2-closure/unit1.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'use strict';
2+
3+
const fs = require('node:fs');
4+
5+
const { readFile } = fs;
6+
7+
let calls = 0;
8+
let callbacks = 0;
9+
10+
fs.readFile = (fileName, callback) => {
11+
calls++;
12+
console.log('call');
13+
readFile(fileName, (error, data) => {
14+
callbacks++;
15+
console.log('callback');
16+
callback(error, data);
17+
});
18+
};
19+
20+
module.exports = () => {
21+
console.log('unit1');
22+
console.log({ calls, callbacks });
23+
return { calls, callbacks };
24+
};

NodeJS/2-closure/unit2.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
'use strict';
2+
3+
const fs = require('node:fs');
4+
5+
fs.readFile('./main.js', (error, data) => {
6+
if (error) {
7+
console.log({ error });
8+
} else {
9+
console.log({ data });
10+
}
11+
});
12+
13+
module.exports = () => {
14+
console.log('unit2');
15+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy