nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
104.76k stars 28.3k forks source link

`require.cache` is `undefined` in SEA #49163

Open pqnet opened 10 months ago

pqnet commented 10 months ago

Version

v20.4.0 v20.5.1 v20.3.0

Platform

Linux 5.15.90.1-microsoft-standard-WSL2

Subsystem

No response

What steps will reproduce the bug?

echo 'console.log(typeof require.cache)' > main.js
node main.js
echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json
node --experimental-sea-config sea-config.json
cp $(command -v node) hello
npx postject hello NODE_SEA_BLOB sea-prep.blob --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2
./hello

How often does it reproduce? Is there a required condition?

Always reproducible

What is the expected behavior? Why is that the expected behavior?

require.cache should be an object as of https://nodejs.org/api/modules.html#requirecache

What do you see instead?

require.cache is undefined. Trying to index it or enumerate it with Object.entries will result in TypeError

Additional information

This is relevant for Fastify which uses cache to provide a printable name for a plugin (based on its file path). See https://github.com/fastify/fastify/blob/c235d2dc136a67c51095f188742c743d8cb32839/lib/pluginUtils.js#L27

pqnet commented 10 months ago

Workaround for Fastify: require.cache can be polyfilled with

if (typeof require !== 'undefined' && typeof require.cache === 'undefined') {
    require.cache = {}
}
pqnet commented 10 months ago

also https://github.com/nodejs/node/blob/de4553f3d11f07fa63e19069daa1b0890052d8b2/test/fixtures/sea.js#L42

itPiligrim commented 4 weeks ago

For Fastify or other that can also be achieved: const { createRequire } = require('node:module'); require = createRequire(__filename); See: https://nodejs.org/api/single-executable-applications.html#requireid-in-the-injected-main-script-is-not-file-based