Skip to content
File

Blob: samples/nodejs-compat/worker.js

javascript90 lines
1import { EventEmitter } from 'node:events';
2import { Buffer } from 'node:buffer';
3import {
4 ok,
5 deepStrictEqual,
6 throws,
7} from 'node:assert';
8import {
9 callbackify,
10 promisify,
11 format,
12} from 'node:util';
13 
14import { default as path } from 'node:path';
15 
16console.log(path.resolve('a', 'b', 'c'));
17console.log(path.basename('/a/b/c/d.foo'));
18console.log(path.extname('/a/b/c/d.foo'));
19 
20// Note that the path.win32 variants of the path API are not yet implemented.
21// While workerd is capable of running on Windows, we assume that the environment
22// is POSIX-like for now.
23throws(() => path.win32.resolve('a', 'b', 'c'), {
24 message: 'path.win32.resolve() is not implemented.'
25});
26 
27// Callback function
28function doSomething(a, cb) {
29 setTimeout(() => cb(null, a), 1);
30}
31 
32// Async function
33async function promiseSomething(a) {
34 await scheduler.wait(1);
35 return a;
36}
37 
38const promisified = promisify(doSomething);
39const callbackified = callbackify(promiseSomething);
40 
41export default {
42 async fetch(request) {
43 let res;
44 const promise = new Promise((a) => res = a);
45 
46 // Util promisify/callbackify
47 console.log(await promisified(321));
48 
49 callbackified(123, (err, val) => {
50 console.log(err, val);
51 });
52 
53 // The events module...
54 const ee = new EventEmitter();
55 ee.on('foo', () => {
56 
57 // The assertion module...
58 ok(true);
59 deepStrictEqual({
60 a: {
61 b: new Set([1,2,3]),
62 c: [
63 new Map([['a','b']])
64 ]
65 }
66 }, {
67 a: {
68 b: new Set([1,2,3]),
69 c: [
70 new Map([['a','b']])
71 ]
72 }
73 });
74 throws(() => {
75 // util.format
76 throw new Error(format('%s', 'boom'));
77 }, new Error('boom'));
78 // The buffer module...
79 const buffer = Buffer.concat([Buffer.from('Hello '), Buffer.from('There')], 12);
80 buffer.fill(Buffer.from('!!'), 11);
81 
82 res(new Response(buffer));
83 });
84 
85 setTimeout(() => ee.emit('foo'), 10);
86 
87 return promise;
88 }
89};