lib/gc.js

/**
 * @module pete/lib/gc
 */
module.exports = exposeGC();

/**
 * Expose `gc()` method, even if there was no `--expose-gc` flag set in CLI.
 *
 * @alias module:pete/lib/gc
 * @type {Function}
 * @see {@link https://github.com/nodejs/node/issues/16595#issuecomment-340288680}
 * @return {Function}
 */
function exposeGC () {
	if (typeof global.gc === 'function') {
		return global.gc;
	}

	try {
		require('node:v8').setFlagsFromString('--expose_gc'); // eslint-disable-line global-require
	}
	catch (e) { // eslint-disable-line no-unused-vars
		console.error('The `gc()` function is not exposed and `setFlagsFromString` is not available or failed. Try running with `--expose-gc` option.');
		if (typeof global.Bun === 'undefined') {
			console.error('See: https://nodejs.org/docs/latest/api/cli.html#--expose-gc for more info.');
		}
		else {
			console.error('See: https://bun.sh/docs/cli/run for more info.');
		}
		const fakeGC = () => {}; // eslint-disable-line no-empty-function
		fakeGC.isFake = true;
		return fakeGC;
	}

	return require('node:vm').runInNewContext('gc'); // eslint-disable-line global-require
}