From 4f5d6d352a763d2b506e5b2af07f48ae520f9d05 Mon Sep 17 00:00:00 2001 From: Alon Zakai Date: Thu, 22 Sep 2022 15:17:22 -0700 Subject: [PATCH] Node FS: Guard on require() existing before requiring. See #17851 --- src/node_shell_read.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/node_shell_read.js b/src/node_shell_read.js index c47176de3cbbf..2a7fce592b9aa 100644 --- a/src/node_shell_read.js +++ b/src/node_shell_read.js @@ -4,9 +4,20 @@ * SPDX-License-Identifier: MIT */ -// These modules will usually be used on Node.js. -var fs = require('fs'); -var nodePath = require('path'); +// These modules will usually be used on Node.js. Load them eagerly to avoid +// the complexity of lazy-loading. However, for now we must guard on require() +// actually existing: if the JS is put in a .mjs file (ES6 module) and run on +// node, then we'll detect node as the environment and get here, but require() +// does not exist (since ES6 modules should use |import|). If the code actually +// uses the node filesystem then it will crash, of course, but in the case of +// code that never uses it we don't want to crash here, so the guarding if lets +// such code work properly. See discussion in +// https://github.com/emscripten-core/emscripten/pull/17851 +var fs, nodePath; +if (typeof require === 'function') { + fs = require('fs'); + nodePath = require('path'); +} read_ = (filename, binary) => { #if SUPPORT_BASE64_EMBEDDING