我是 Browserify 的新手并尝试以下操作:
我创建了一个 Node 服务器并尝试在浏览器上运行一个名为“openbci”的包。

所以我有以下文件结构:

Myapp
-...
-public
--app.js
--index.html
--openBCI.js
--...
--javascript
---openBCI
----bundle.js
---...
-node_modules
--openbci
---openBCIBoard.js
--browserify
--...

我的 app.js 文件将服务器设置为为 public 文件夹提供服务
// app.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.listen(myPort);

然后我创建了以下 openBCI.js
// openBCI.js
var OpenBCIBoard = require('openbci').OpenBCIBoard;
exports.OpenBCIBoard = OpenBCIBoard;

最后启动了 browserify 命令:
$ browserify public/openBCI.js > public/javascript/openBCI/bundle.js

但是一旦在我的 index.html 文件中调用,我在 Function.getRoot 处得到了一个 Uncaught TypeError: exists is not a function:
exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    **if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {**
      // Found the 'package.json' file or 'node_modules' dir; we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: "' + file
                    + '". Do you have a `package.json` file? ')
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}

似乎找不到模块的原始路径。
你能告诉我要改变什么吗?或者,如果我完全理解 browserify 是如何工作的? :)

最佳答案

我注意到代码中有一些看起来很奇怪的地方。

  • exists 在 JavaScript 或 Node 中未定义。它似乎是 fs.exists 的别名 - 是吗?

  • 如果是这样,不推荐使用 fs.exists。根据文档,您可以使用 fs.statfs.access 实现相同的效果。但是请注意,您应该提供回调(最好)或使用这些方法的同步版本。
  • 如果您尝试在浏览器中使用文件系统工具,您将遇到问题,因为您试图从浏览器访问服务器的文件系统。有一个插件 browserify-fs ,它在浏览器中为您提供等效于 fs 的功能。但是,这似乎访问浏览器的本地 IndexedDB,而不是服务器上的存储。

  • 我建议在服务器上运行依赖于服务器端文件的代码,而不是在浏览器中。

    关于javascript - Nodejs Browserify Uncaught TypeError : exists is not a function,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41681498/

    10-11 00:53
    查看更多