-1

Main: How do i require modules that have example field in it's package.json?

For example:

const path = require( "path" );
const glob = require( "glob" );

const modules = glob.sync( './node_modules/*' );

for ( let mod in modules ) {
    const modPackage = require( path.resolve( __dirname, "node_modules", mod, "package.json" ) );
    if ( modPackage.hasOwnProperty( "example" ) ) {
        console.log( "Module:", mod, "Has Field 'example'" );
    }
}

Addiotinal: How do i require modules that have a specific tag? (for example: "demo")

Hasan Bayat
  • 926
  • 1
  • 13
  • 24
  • your question is ambiguous , what you grammatically as in the name, is that you want a search in package.json for a particular file but you do not want to invoke that file. please elaborate – Remario Mar 18 '17 at 10:55
  • I fixed it. but you read entire content for main question. – Hasan Bayat Mar 18 '17 at 11:00

1 Answers1

0

It looks to me like your code is basically correct, just two issues:

  1. You wanted for-of, not for-in.
  2. No need to add /node_modules/ to the path.

So:

const path = require( "path" );
const glob = require( "glob" );

const modules = glob.sync( './node_modules/*' );

for (let mod of modules ) {
// ----------^^
    const modPackage = require( path.resolve( __dirname, mod, "package.json" ) );
// ------------------------------------------------------^
    if ( modPackage.hasOwnProperty( "example" ) ) {
        console.log( "Module:", mod, "Has Field 'example'" );
    }
}

You almost never want to use for-in on arrays. More about looping through arrays in this question's answers.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875