Skip to content

Commit 863a68a

Browse files
committed
Add polyfill module implementing NodeJS behavior
Module implements standard js console, import/export like NodeJS, timer routines (setTimeout, clearTimeout, etc.) and other.
1 parent 63b4012 commit 863a68a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

fs/polyfill.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// TODO: implement error & warn/debug/stack methods
2+
let console = {log: print, error: print};
3+
let module = {exports: null, _cache: {}};
4+
5+
function require(path) {
6+
// Prevent duplicate load, return from cache
7+
let c = module._cache[path];
8+
if (c !== undefined) {
9+
return c;
10+
}
11+
12+
// noinspection JSUnresolvedFunction
13+
load(path);
14+
15+
// Add module to cache
16+
c = module._cache[path] = module.exports;
17+
// clean exports data to prevent modules duplication
18+
module.exports = undefined;
19+
20+
return c;
21+
}
22+
23+
// Load Timer lib only on demand & cache result
24+
let __timer = null;
25+
26+
function __getTimer() {
27+
if (!__timer) {
28+
// TODO: add module.export to api_timer & use require with caching
29+
// noinspection JSUnresolvedFunction
30+
load('api_timer.js');
31+
32+
__timer = Timer;
33+
}
34+
35+
return __timer;
36+
}
37+
38+
function setInterval(fn, timeout) {
39+
let t = __getTimer();
40+
41+
return t.set(timeout, t.REPEAT, fn, null);
42+
}
43+
44+
function setTimeout(fn, timeout) {
45+
return __getTimer().set(timeout, 0, fn, null);
46+
}
47+
48+
function clearTimeout(id) {
49+
return __getTimer().del(id);
50+
}
51+
52+
function clearInterval(id) {
53+
return clearTimeout(id);
54+
}

0 commit comments

Comments
 (0)