Browserify the node.js http server

2019-07-16 06:34发布

问题:

We created a simple js file, intending to find out if http.createServer works on client browser or not:

var http = require("http")
var server = http.createServer()
server.listen(9024, function () {
    console.log("demo server listening on port 9024")
})

and embedded it into a html after browserify.

Display the html in chrome, unfortunately, it always fails on line 2 on http.createServer():

"Uncaught Type Error: undefined is not a function"

We also played around with "serve-browserify" a bit without success.

We have attempted the same thing on both chrome and firefox, and on Linux and Windows. All failed. Searching through the web, there are quite a few examples for browserify http into the browser. They all appear to be simple invocation of browserify. However we don't seem to be able to get the same good result. Your help will be greately appreciated.

回答1:

You can't use Node.js modules in the browser. All Browserify does is bundling CommonJS modules, it does not allow you to run server side code in the browser.