主要:我如何要求example
中包含package.json
字段的模块?
例如:
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”)
答案 0 :(得分:0)
在我看来,您的代码基本上是正确的,只有两个问题:
for-of
,而不是for-in
。/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中循环遍历数组的更多信息。