I’m working on a Node.js project and I’m curious about something. Is there a way to see what NPM packages my app is using while it’s running? I know I can look at the package.json
file, but I’m wondering if there’s another method. Maybe Node keeps this info somewhere I can access?
Here’s a simple example of what I mean:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
// How can I get a list of dependencies here?
Does anyone know if there’s a way to get this info from inside the running app? Thanks for any help!
yo, have u checked out the ‘process.modules’ object? it’s pretty handy for this kinda stuff. just do a console.log(Object.keys(process.modules)) in ur running app and it’ll show u all the loaded modules. not perfect, but it gives u a good idea of whats going on under the hood.
While the other responses offer some good insights, there’s another approach worth considering. You can use the ‘npm list’ command in your terminal to see a tree of all installed packages, including their dependencies. For a running application, you might consider implementing a route or endpoint that executes this command and returns the result.
Here’s a basic example:
const { exec } = require('child_process');
app.get('/packages', (req, res) => {
exec('npm list --json', (error, stdout, stderr) => {
if (error) {
res.status(500).send(error);
return;
}
res.send(JSON.parse(stdout));
});
});
This method provides a comprehensive view of your dependencies, including nested ones, which can be quite useful for debugging or auditing purposes.
I’ve actually faced this exact situation before! In my experience, there are a couple of ways to approach this. One method I’ve found particularly useful is using the process.mainModule.children
array. This gives you access to all the loaded modules.
Here’s a quick snippet I’ve used in the past:
const modules = process.mainModule.children.map(child => child.filename);
console.log(modules);
This will log out the filenames of all loaded modules. It’s not perfect, as it doesn’t directly map to npm package names, but it’s a good starting point.
Another approach I’ve used is the require.cache
object. It contains references to all loaded modules. You can iterate over it like this:
Object.keys(require.cache).forEach(key => {
console.log(key);
});
These methods aren’t foolproof, but they’ve helped me debug and understand my running applications better. Hope this helps!