我应该硬编码引用到我的node_modules文件夹?

我创build一个名为ctgen的npm包,我需要引用该包内的文件夹。 我应该硬编码的文件夹的引用?

例如src = './node_modules/ctgen/scaffold'

还是有一个预制的function,将为我做这个?

在我的问题上更清晰一点。 我的包中有以下function:

 var createFile = function (fileName, componentName, doc) { // Tell the user what is happening console.log(chalk.blue('\nCreating', fileName, '...')) // Bring in the scaffold files (note this should point to the scaffold folder in node modules/ctgen) var scaffold = './scaffold/' + fileName fs.readFile(scaffold, 'utf8', function (err, data) { if (err) return console.log(chalk.red(err)) var result = data.replace(/%cname%/g, componentName) if (doc) { var d = new Date() result = result.replace(/%cfname%/g, doc.componentName) result = result.replace(/%cdesc%/g, doc.componentDesc) result = result.replace(/%cauthor%/g, doc.userName) result = result.replace(/%cagithub%/g, doc.userGithub) result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear()) } fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) { if (err) return console.log(chalk.red(err)) console.log(chalk.green(fileName, 'created!')) }) }) } 

它在一个名为scaffold的文件夹中查找以下文件:

  • view.php
  • style.styl
  • component.json

然后将文件拖入caching,执行查找并replace某些string,然后将输出写入用户项目中的文件。

它似乎虽然每当我尝试引用'scaffold'文件夹,它试图find它在用户项目文件夹,而不是在我的包文件夹。

我很犹豫是通过写'/node_modules/ctgen/scaffold'来引用scaffold文件夹,因为这对我来说似乎是错误的。

你想要的是__dirname

如果我理解你的问题,你有一个包含在你的模块的资源文件夹,并且无法访问它,因为当前path是应用程序的path,而不是你的模块。

__dirname将包含您的脚本文件的path,所以将指向您的模块文件。

我假设你的模块被命名为ctgen,并且你想要访问的文件在ctgen / scaffold中。 所以在你的代码中,尝试访问__dirname/scaffold

总之NO 。 如果您想了解更多关于节点如何查找所需文件的请求,请阅读以下内容: https : //nodejs.org/dist/latest-v7.x/docs/api/modules.html#modules_addenda_package_manager_tips

如果你正在创build一个npm包,在你的package.json指定你的依赖npm模块,并在节点中使用它们(使用require('your-dependent-module-name') )。 在你发布你的模块和某人npm install --save your-module ,它也会把你的依赖关系安装到你的模块将会find它所需要的[usrDir]/node_modules/[your-module]/node_modules中。

那家伙说: 是的,你可以参考__dirname + 'node_modules/[something]但这不会很聪明,因为它假设用户如何使用你的模块。 同时,node + npm为你解决了这个问题,所以你没有理由要这样做)