readable-stream icon indicating copy to clipboard operation
readable-stream copied to clipboard

cannot use readable-stream on service worker

Open userquin opened this issue 2 years ago • 2 comments

I patch these 2 modules with a postinstall script ("postinstall": "esno scripts/patch.ts"):

import { readFileSync, writeFileSync } from 'node:fs'

const patch = () => {
    let content: string = readFileSync(
        './node_modules/readable-stream/lib/_stream_readable.js',
        { encoding: 'utf-8' },
    )
    if (content.includes('global.Uint8Array')) {
        writeFileSync(
            './node_modules/readable-stream/lib/_stream_readable.js',
            content.replace(
                'var OurUint8Array = global.Uint8Array || function () {};',
                'var OurUint8Array = self.Uint8Array || function () {};'
            ),
            { encoding: 'utf-8' },
        )
    }
    content = readFileSync('./node_modules/readable-stream/lib/_stream_writable.js', { encoding: 'utf-8' })
    if (content.includes('global.Uint8Array')) {
        writeFileSync(
            './node_modules/readable-stream/lib/_stream_writable.js',
            content.replace(
                'var OurUint8Array = global.Uint8Array || function () {};',
                'var OurUint8Array = self.Uint8Array || function () {};'
            ),
            { encoding: 'utf-8' },
        )
    }
}

patch()

userquin avatar Sep 08 '22 21:09 userquin

Rather than just assuming global will be defined, probably need to do something like:

typeof global !== "undefined"
  ? global
  : typeof self !== "undefined"
  ? self
  : typeof window !== "undefined"
  ? window
  : {};

E.g. as done in https://github.com/Aslemammad/modern-node-polyfills/blob/main/global.ts

benmccann avatar Sep 08 '22 21:09 benmccann

Would you like to send a PR? Checkout our build scripts inside build/.

mcollina avatar Sep 08 '22 21:09 mcollina

Mark as closed by https://github.com/nodejs/readable-stream/pull/502

smeng9 avatar Mar 01 '23 02:03 smeng9