diff --git a/lib/detect-libc.js b/lib/detect-libc.js index fe49987..0087947 100644 --- a/lib/detect-libc.js +++ b/lib/detect-libc.js @@ -3,7 +3,8 @@ 'use strict'; -const childProcess = require('child_process'); +const { safeRequire } = require('./utils'); +const childProcess = safeRequire('child_process', 'node:child_process'); const { isLinux, getReport } = require('./process'); const { LDD_PATH, readFile, readFileSync } = require('./filesystem'); @@ -16,10 +17,13 @@ let commandOut = ''; const safeCommand = () => { if (!commandOut) { return new Promise((resolve) => { - childProcess.exec(command, (err, out) => { - commandOut = err ? ' ' : out; - resolve(commandOut); - }); + // null check + if (childProcess) { + childProcess.exec(command, (err, out) => { + commandOut = err ? ' ' : out; + resolve(commandOut); + }); + } }); } return commandOut; @@ -28,6 +32,7 @@ const safeCommand = () => { const safeCommandSync = () => { if (!commandOut) { try { + // No null check needed since the error will be caught commandOut = childProcess.execSync(command, { encoding: 'utf8' }); } catch (_err) { commandOut = ' '; diff --git a/lib/filesystem.js b/lib/filesystem.js index de7e007..e863b0a 100644 --- a/lib/filesystem.js +++ b/lib/filesystem.js @@ -3,7 +3,8 @@ 'use strict'; -const fs = require('fs'); +const { safeRequire } = require('./utils'); +const fs = safeRequire('fs', 'node:fs'); /** * The path where we can find the ldd @@ -16,7 +17,7 @@ const LDD_PATH = '/usr/bin/ldd'; * @param {string} path * @returns {string} */ -const readFileSync = (path) => fs.readFileSync(path, 'utf-8'); +const readFileSync = (path) => fs ? fs.readFileSync(path, 'utf-8') : null; /** * Read the content of a file @@ -25,13 +26,16 @@ const readFileSync = (path) => fs.readFileSync(path, 'utf-8'); * @returns {Promise} */ const readFile = (path) => new Promise((resolve, reject) => { - fs.readFile(path, 'utf-8', (err, data) => { - if (err) { - reject(err); - } else { - resolve(data); - } - }); + // null check + if (fs) { + fs.readFile(path, 'utf-8', (err, data) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + } }); module.exports = { diff --git a/lib/utils.js b/lib/utils.js new file mode 100644 index 0000000..63bb2b3 --- /dev/null +++ b/lib/utils.js @@ -0,0 +1,23 @@ +'use strict'; + +// Safe require +const safeRequire = (moduleName, ...fallbacks) => { + try { + // Try to require the primary module + return require(moduleName); + } catch (error) { + // If module not found, try fallbacks + for (let i = 0; i < fallbacks.length; i++) { + const fallback = fallbacks[i]; + try { + return require(fallback); + } catch (fallbackError) { + // Skip to the next fallback if it fails + } + } + + return null; + } +}; + +module.exports = { safeRequire };