我正在创建一个名为ctgen
的npm包,我需要引用该包中的文件夹。我应该硬编码该文件夹的引用吗?
e.g。 src = './node_modules/ctgen/scaffold'
还是有预制的功能会为我做这个吗?
为了更清楚我的问题。我的包中有以下功能:
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的文件夹中查找以下文件:
然后将文件拉入缓存,对某些字符串执行查找和替换,然后将输出写入用户项目中的文件。
似乎每当我尝试引用'scaffold'
文件夹时,它都会尝试在用户项目文件夹中找到它,而不是在我的包文件夹中找到它。
通过编写'/node_modules/ctgen/scaffold'
来引用scaffold文件夹我非常犹豫,因为这对我来说似乎是错误的。
答案 0 :(得分:2)
你想要的是__dirname
。
如果我理解您的问题,您的模块中包含一个ressource文件夹,并且无法访问它,因为当前路径是应用程序的路径,而不是您的模块。
__dirname
将包含脚本文件的路径,因此将指向您的模块文件。
我假设您的模块名为ctgen,您要访问的文件位于ctgen / scaffold中。因此,在您的代码中,请尝试访问__dirname/scaffold
。
答案 1 :(得分:0)
简而言之否。如果您想了解有关节点如何查找所需文件的更多信息请阅读:https://nodejs.org/dist/latest-v7.x/docs/api/modules.html#modules_addenda_package_manager_tips
答案 2 :(得分:0)
如果要创建npm包,请在package.json
中指定相关的npm模块,并在节点中使用它们(使用require('your-dependent-module-name')
)。在您发布模块和某人npm install --save your-module
之后,它还会将您的依赖项安装到[usrDir]/node_modules/[your-module]/node_modules
,您的模块将在其中找到所需内容。
那个说法;是的,你可以引用__dirname + 'node_modules/[something]
,但这不会很聪明,因为它会假设用户如何使用你的模块。同时,node + npm为您解决了这个问题,因此没有理由要这样做)