【问题标题】:Traversing directory in Node (Grunt)在 Node 中遍历目录(Grunt)
【发布时间】:2014-06-21 23:24:45
【问题描述】:

在构建grunt plugin 时遇到一个奇怪的问题。

基本上,我想在我的 grunt 任务本身中使用 node_module。为此,我想向上遍历一个级别,然后向下遍历节点模块以专门调用它们的一个文件。

最初,我想这样做:

../node_modules/github-changes/bin/index.js

但是,我收到以下错误:

Warning: Command failed: /bin/sh: 1: ../node_modules/github-changes/bin/index.js: not found
Use --force to continue.

所以,现在我对使用 Node 的 __dirname 变量有一些技巧,但它不是很漂亮:

var dirHack = __dirname.replace("/tasks", ""), // Terrible hack, need to fix
       ghC = dirHack + '/node_modules/github-changes/bin/index.js';

这可行,但我想避免它。

你可以看到here这一行。

缺少什么导致该错误?我在这里遗漏了什么吗?

【问题讨论】:

    标签: javascript node.js directory gruntjs traversal


    【解决方案1】:

    如果github-changes 是一个依赖项,您可以使用ghC = require.resolve('github-changes/bin/index.js') 解析包内文件的路径。

    但是您收到该错误是因为您尝试将该文件作为 shell 脚本运行,但事实并非如此。您需要使用节点运行它。找到节点可执行文件路径的最简单方法是process.execPath。见http://nodejs.org/api/process.html#process_process_execpath

    这是一个例子:

    var exec = require('child_process').exec;
    var ghC = require.resolve('github-changes/bin/index.js');
    exec(process.execPath + ' ' + ghC, function(error) {});
    

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 2016-01-22
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      相关资源
      最近更新 更多