node.js - 我应该硬编码对我的node_modules 文件夹的引用吗?

标签 node.js npm

我正在创建一个名为 ctgen 的 npm 包,我需要引用该包中的一个文件夹。我应该硬编码对该文件夹的引用吗?

例如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的文件夹中查找以下文件:

  • view.php
  • 样式.styl
  • 组件.json

然后它将文件提取到缓存中,对某些字符串执行查找和替换,然后将输出写入用户项目中的文件。

似乎每当我尝试引用 'scaffold' 文件夹时,它都会尝试在用户项目文件夹中而不是在我的包文件夹中找到它。

我非常犹豫是否要通过编写 '/node_modules/ctgen/scaffold' 来引用脚手架文件夹,因为这对我来说似乎是错误的做法。

最佳答案

你想要的是__dirname

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

__dirname 将包含脚本文件的路径,因此将指向您的模块文件。

我假设您的模块名为 ctgen,并且您要访问的文件位于 ctgen/scaffold 中。因此,在您的代码中,尝试访问 __dirname/scaffold

关于node.js - 我应该硬编码对我的node_modules 文件夹的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43184298/

相关文章:

jQuery 与 EJS

node.js - 当不存在 Waterline 关联时 Sails 服务返回 MongoDb 结果,但当它们存在时失败

node.js - Npm 包安装失败 - 如何恢复旧的工作版本?

node.js - 如何在 Nodejs 启动 npm 之前进行 git pull

cordova - Ionic 错误,无法验证第一个证书

mysql - 如何在node.js-sql中通过绑定(bind)参数构建动态查询?

用于 socket.io 服务器的 Node.js 客户端

json - 从 JSON 文件定义 Mongoose 模式

node.js - 发生未处理的异常 : Job name "..getProjectMetadata" does not exist

javascript - 覆盖 npm 包依赖