Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js List All Modules Required in a File

I must be missing something here. I have a mocha test file that is set up like so:

require('globals');
var library1 = require('library1'),
  library2 = require('library2');

it('tests stuff', function() {
  ...
});

Where the globals file just contains a before and afterEach block, so that they apply to all my test files.

What I'm trying to do is determine, within the before and afterEach blocks, which files that I have require'd in the test file that those blocks are currently running in. So in the example test file I gave, I would need afterEach to output a list that contains globals, library1, and library2.

I have attempted to use Node.js's module.children property, but for some reason that is only returning me globals, and excluding library1 and library2.

Edit: What am I missing that module.children wouldn't be returning library1 and library2?

like image 396
Ryan McDonald Avatar asked Sep 16 '25 08:09

Ryan McDonald


1 Answers

Here is an example of a script that will parse requires in a file.

var fs = require('fs');

function parseRequires(absPath){
    var requiredFiles = [];
    var contents = fs.readFileSync(absPath, 'utf8').split('\n');

    contents.forEach(function(line){
        var re = /(?:require\('?"?)(.*?)(?:'?"?\))/;
        var matches = re.exec(line);

        if(matches){
            requiredFiles.push(matches[1]);
        }

    });

    return requiredFiles;

}

module.exports = parseRequires;

I made a test script in the same directory

var fs = require('fs');
var os = require('os');

function A(){}

var http = require("http");

var parseRequires = require("./parseRequires");

console.log( parseRequires( __dirname + '/testRequires.js') );

results in console: [ 'fs', 'os', 'http', './parseRequires' ]

This is one solution, though I'm sure there is an easier way to do it with nodejs built in functionality

like image 165
Gabs00 Avatar answered Sep 17 '25 21:09

Gabs00