browserify Error : http.createServer is not a function

browserify Error : http.createServer is not a function

我尝试浏览此节点 js 脚本:

var phantom = require('phantom')
phantom.create(function(ph) {
ph.createPage(function(page) {
    page.open("editor.html", function(status) {
        console.log("opened diagram? ", status);
        page.evaluate(function() {
            return document.getElementById("GraphImage").src;
        }, function(result) {
            //console.log(result);
            ph.exit();
        });
    });
});
});

所以我使用了这个命令:

browserify myscript.js > bundle.js

当我从 html 文件 运行 bundle.js 时,我收到此错误:

http.createServer is not a function 

看来browserify 不支持httpserver。我该如何解决这个问题?

您不能从网络浏览器中 运行 网络服务器。浏览器中确实没有任何东西可以像 Node 的 http 模块那样工作。在浏览器中 运行 PhantomJS 也没有意义,因为 PhantomJS 网络浏览器。

您想要实现的行为是什么?


更新:

您似乎正试图在浏览器中 运行 用于 Node.js 的代码。

浏览器中的 JavaScript 引擎比 Node.js 中的引擎更加严格,例如出于安全原因您不能从浏览器内部访问文件系统(否则您可以阅读任何访问过您网页的人的硬盘)。

Browserify include some "shims" 会将小型 JS 库放入可在浏览器中运行的代码中,并匹配 Node.js 的 API,允许 一些 Node.js 要在浏览器中执行的特定 JS 代码。

在您的情况下,您需要 Phantom,这似乎又需要 http。根据 Browserify 文档,它将看到 require('http') 并包含 a shim for the http module(因为浏览器不提供自己的 http 模块)。

Phantom 模块然后尝试调用 http.createServer() 但根据该 http shim 的文档:

This module implements http.request, http.get, and most of http.ClientRequest and http.IncomingMessage in addition to http.METHODS and http.STATUS_CODES.

所以 shim 不支持 http.createServer()。这也是有道理的,因为浏览器永远不会让您打开其内部的 http 服务器,否则导航到某人的网站可能会导致您的浏览器开始向外界提供内容,这显然没有意义。

在您的评论中:

"i want that my node js script can be executed from another JS code"

您没有指定 "other JS code" 是 运行ning 的内容。如果该 JS 代码已经 运行ning 在 Node 中,那么您根本不需要 Browserify。如果你试图让网络浏览器启动一个实际的 Node.js 进程,那是不会发生的,再次出于明显的安全原因,因为浏览网页不应该 运行 系统上的任何可执行文件。

Browserify 让您做的是将原本用于 Node.js 的代码改为 运行 在浏览器中使用,但 运行 它在浏览器中执行时,而不是在 Node.js 中,因此您只能使用在浏览器 JS 运行time.

限制内工作的 JS 代码

如果您试图在 Node.js 中执行您的代码,那么您需要通过启动 Node.js 可执行文件来实现,可以从命令行或让另一个程序启动为您处理,但这不能在 Web 浏览器中完成。如果您试图让用户导航到您的网站,然后在他们的机器上的浏览器中而不是在 Node.js 中使用此代码 运行,那么您只需要使用在浏览器中工作的模块。