What is find-requires?
The find-requires npm package is a tool for analyzing JavaScript code to find and list all the require statements. It is useful for understanding dependencies in a codebase, refactoring, or simply auditing the use of modules.
What are find-requires's main functionalities?
Find all require statements in a file
This feature allows you to find all the require statements in a given JavaScript file. The code reads the content of a file and uses the find-requires package to extract all the require statements.
const findRequires = require('find-requires');
const fs = require('fs');
const fileContent = fs.readFileSync('path/to/your/file.js', 'utf8');
const requires = findRequires(fileContent);
console.log(requires);
Find require statements with options
This feature allows you to find require statements with additional options. For example, setting the 'raw' option to true will return the raw AST nodes instead of just the module names.
const findRequires = require('find-requires');
const fs = require('fs');
const fileContent = fs.readFileSync('path/to/your/file.js', 'utf8');
const options = { raw: true };
const requires = findRequires(fileContent, options);
console.log(requires);
Other packages similar to find-requires
detective
The detective package is a similar tool that parses JavaScript code to find all the require statements. It is highly configurable and can be used with various parsers. Compared to find-requires, detective offers more flexibility in terms of parser options and supports ES6 import statements.
precinct
Precinct is another package that can find dependencies in JavaScript code, including both require and import statements. It supports multiple file types and can be extended with custom parsers. Precinct provides a more comprehensive solution for dependency detection compared to find-requires.
find-requires – Find all require() calls.
Made for modules-webmake. Fast esniff based implementation of require calls parser.
Example
foo.js:
var one = require("one");
var two = require("two");
var slp = require("some/long" + "/path");
var wrong = require(cannotTakeThat);
program.js:
var fs = require("fs");
var findRequires = require("find-requires");
var src = fs.readFileSync("foo.js", "utf-8");
console.log(findRequires(src));
console.log(findRequires(src, { raw: true }));
console.log(
findRequires("require(__dirname + '/foo.js')", {
setupCode: `const __dirname = ${ JSON.stringify(__dirname) }`
})
);
CLI Example
> npm install -g find-requires
Find all requires in a file:
> find-requires file1.js
test1.js:3:LIB + '/test2'
test1.js:4:fs
Find all places the fs module is required: find-requires -m fs $(find . -name '*.js')
Tests
$ npm test