Node.js: 如何搜索指定字段的模块?

Node.js: How to search for modules that have a specified field?

Main:我如何要求 package.json 中具有 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:我如何要求具有特定标签的模块? (例如:"demo")

在我看来你的代码基本上是正确的,只有两个问题:

  1. 你想要 for-of,而不是 for-in
  2. 无需在路径中添加/node_modules/

所以:

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'" );
    }
}

您几乎不想在数组上使用 for-in。有关在 this question's answers.

中遍历数组的更多信息