Skip to content

Commit 5508faf

Browse files
committed
Rewrite lstat in 3 different styles
1 parent 1fd0f32 commit 5508faf

File tree

4 files changed

+76
-0
lines changed

4 files changed

+76
-0
lines changed

JavaScript/4-lstat-bad.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'use strict';
2+
3+
const fs = require('node:fs');
4+
5+
const files = ['1-readFileSync.js', 'n-untitled.js', '3-async.js'];
6+
7+
const stats = new Array(files.length);
8+
9+
let rest = files.length;
10+
11+
const printResult = () => {
12+
console.dir({ stats });
13+
};
14+
15+
files.forEach((file, i) => {
16+
console.dir({ file, i });
17+
fs.lstat(file, (err, stat) => {
18+
if (err) {
19+
console.log(`File ${file} not found`);
20+
} else {
21+
stats[i] = stat;
22+
}
23+
if (--rest) return;
24+
printResult();
25+
});
26+
});

JavaScript/4-lstat-callback.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 fs = require('node:fs');
4+
5+
const stats = (files, done) => {
6+
const result = {};
7+
for (const file of files) {
8+
const res = {};
9+
fs.lstat(file, (err, stat) => {
10+
result[file] = { err, stat };
11+
const count = Object.keys(result).length;
12+
if (count === files.length) done(result);
13+
});
14+
}
15+
};
16+
17+
const files = ['1-readFileSync.js', 'n-untitled.js', '3-async.js'];
18+
stats(files, console.dir);

JavaScript/4-lstat-collector.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
3+
const fs = require('node:fs');
4+
5+
class KeyCollector {
6+
constructor(keys, onDone) {
7+
this.expected = new Set(keys);
8+
this.onDone = onDone;
9+
this.finished = false;
10+
this.data = new Map();
11+
}
12+
13+
collect(key, value) {
14+
if (this.finished) return this;
15+
this.data.set(key, value);
16+
if (this.expected.size === this.data.size) {
17+
this.finished = true;
18+
this.onDone(this.data);
19+
}
20+
return this;
21+
}
22+
}
23+
24+
const files = ['1-readFileSync.js', 'n-untitled.js', '3-async.js'];
25+
26+
const stats = new KeyCollector(files, console.dir);
27+
28+
for (const fileName of files) {
29+
fs.lstat(fileName, (err, stat) => {
30+
stats.collect(fileName, err || stat);
31+
});
32+
}
File renamed without changes.

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