Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fix readable-stream in React Native
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const ROOT_PATH = path.resolve(`${__dirname}/..`);
// Get paths to all readable-stream packages in the dependency tree
function getPackagePaths(rootPath, packageName) {
return glob.sync(`${rootPath}/**/node_modules/${packageName}`);
}
// Get paths a package's JavaScript source files, not including dependencies
function getPackageSourceFiles(packagePath) {
return glob.sync(`${packagePath}/**/*.js`, {
ignore: 'node_modules',
});
}
// The readable-stream package calls require() in a way that will cause
// the call to throw an exception when using Webpack or Browserify.
//
// require('st' + 'ream')
//
// This case is handled: the module catches the exception and continues.
// However, when using React Native Packer, the require() call does not throw
// an exception and instead returns an empty object ({}), causing the module
// to eventually throw an error and crash the program.
//
// This function replaces these calls with an inline function that throws an
// error, like module expects.
function patchSourceFile(content) {
return content.replace(
// eslint-disable-next-line
`require('st' + 'ream')`,
// eslint-disable-next-line
`(function() { throw new Error('readable-stream called require(st + ream)') })()`
);
}
console.log('Patching readable-stream...');
// Get source files of all readable-stream packages in the dependency tree
getPackagePaths(ROOT_PATH, 'readable-stream').forEach((packagePath) => {
getPackageSourceFiles(packagePath).forEach((sourceFilePath) => {
// Read the source file and patch it
const content = fs.readFileSync(sourceFilePath, 'utf8');
const patched = patchSourceFile(content);
// If the file content is changed, write to the file
if (content !== patched) {
const relPath = path.relative(ROOT_PATH, sourceFilePath);
console.log(' =>', relPath);
fs.writeFileSync(sourceFilePath, patched, 'utf8');
}
});
});
@chmac
Copy link

chmac commented Dec 1, 2017

@parshap Nice. I would like to use a slightly patched version of this file. Would you consider adding an MIT / BSD style license?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment