browserify Error : http.createServer is not a function - javascript

I tried to browserify this node js script :
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();
});
});
});
});
So I used this command:
browserify myscript.js > bundle.js
and when I run bundle.js from an html file I get this error:
http.createServer is not a function
it seems that browserify does not support httpserver. How can I resolve this problem?

You can't run a web server from inside a web browser. There really isn't anything in the browser that could act like Node's http module. Also it doesn't make sense to run PhantomJS in a browser, because PhantomJS is a web browser.
What is the desired behavior you are trying to accomplish?
Update:
It seems like you are trying to run code intended for Node.js inside a browser instead.
The JavaScript engine inside the browser is much more restrictive than in Node.js, for example you can't access the file system from inside the browser for security reasons (or else you could read the hard drive of anyone who visited your web page).
Browserify does include some "shims" that will put small JS libraries into your code that work in the browser and match the API of Node.js, allowing some Node.js specific JS code to execute in the browser.
In your case, you are requiring Phantom, which seems to in turn require http. Accoring to the Browserify documentation, it will see require('http') and include a shim for the http module (because browser's don't provide an http module of their own).
The Phantom module then tries to call http.createServer() but accoring to the documentation for that 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.
so http.createServer() is not supported by the shim. This also makes sense because a browser would never let you open an http server inside of itself, or else navigation to someone's web site could cause your browser to start serving content to the outside world, which obviously doesn't make sense.
In your comment:
"i want that my node js script can be executed from another JS code"
You don't specify what "other JS code" is running in. If that JS code is already running in Node, then you don't need Browserify at all. If you are trying to have a web browser start up an actual Node.js process, that isn't going to happen, again for obvious security reasons, because browsing to a web page shouldn't have the ability to run any executable on your system.
What Browserify lets you do is take code originally intended for Node.js, and run it in a browser instead, but a t runtime it is executing in the browser, not in Node.js, so you can only use JS code that works within the constraints of the browser's JS runtime.
If you are trying to execute your code in Node.js, then you need to do that by having something start the Node.js executable, either from the command line or by having another program start the process for you, but that can't be done from within a web browser. If you are trying to have users navigate to your web site and then have this code run on their machines in a browser and not in Node.js, then you need to only use modules that work in the browser.

Related

How to connect a Postgres Database to a HTML page with Node.js? [duplicate]

First I dowloaded nodejs from link.
Then I installed browserify npm install -g browserify
Then I installed fs npm install fs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {return console.log(err);}
console.log("The file was saved!");
});
</script>
</body>
</html>
I am getting the following error:
Uncaught ReferenceError: require is not defined
at index.html:12:12
Why require is still not defined? What could I do to get the code to be executable?
Node.js is a stand-alone environment for running JavaScript. It is not a browser extension.
To run Node.js code, save it in a file with a .js file extension, then run it with:
node yourFile.js
If you want Node.js code and browser code to interact then the typical way is to write a server in Node.js that hosts a web service. Express.js is a popular way to do this. You can then use Ajax to make HTTP requests to that web service.
For bi-directional communication (as opposed to the request/response of Ajax) look at Socket.io.
I just want it to be local storage, so I do not want to share the datas between the users, I just want to interact with there own local storage datas.
If you want to use the localStorage API provided by browsers, then do so.
localStorage doesn't need Node.js. It doesn't need the fs module that is built into Node.js. It doesn't need the require method that is part of the CommonJS module specification.
You can't muck around freely on the user's file system from code running in the browser. That would be a huge security problem.
You can't use node APIs in browser environment; more specifically browser won't allow script to directly interact with file APIs like Node.
Either run your code in node as quentin said, or use browser file api

Fetch local files with Node.js

In a browser environment fetching a local file is quite trivial: one just need to start a server (using MAMP, XAMP, Mac's Python server, etc...), and then doing:
fetch("./foo.txt").then(etc...)
However, in Node.js this simple task has been a challenge. I've tried the same snippet using Node 18 (which comes with an experimental fetch API), but I'm always getting an invalid URL error:
TypeError: Failed to parse URL from foo.bar
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
I've tried installing node-fetch, but I'm getting the same error. I could start a local server for node like http-server, but it tells me to go to http://localhost:8080 to see the server, that is, using the browser, but the issue is that I can do that without node, using only a node build is the whole point.
My question is: is it possible to fetch a local file in a node build (Sublime Text, VS Code etc...), without using a browser? (note: I can do it with fs, but in my question I'd like to discuss fetch only)
My question is: is it possible to fetch a local file in a node build (Sublime Text, VS Code etc...), without using a browser? (note: I can do it with fs, but in my question I'd like to discuss fetch only)
The Node.js implementation of fetch does not currently support file: scheme URLs…
fetch("file:///tmp/123").then(r => r.text()).then(d => console.log(d));
reports:
Error: not implemented... yet...
…nor (it appears) does it resolve a relative path to a file: scheme URI.
You should use the fs module.

Handle global variable in node.js server

I have a node.js server that reads messages from a rabbitmq server. Every message contains an url that returns a json object whit specifications to download some jsx code.
The node.js server gets the code from the urls and compiles it with webpack.
My problem is that I need to keep aware of the information of the json objects in the webpack compilation instance, because I need to print the downloaded objects in the index page.
Node Server -- Get messages --> RabbitMQ Server
RabbitMQ Server -- Return messages --> Node Server
Node Server -- Get code [from URL] --> URL service
URL service -- Return code --> Node Server
Node Server: Compile downloaded code.
I don't know if I was clear. I tried to use global variables and module.exports, but did not work. Maybe I am missing something, I am a kind of beginner in JS, node and webpack.
Could you cache those in memory, that way they would be available to access.
One of the popular module is memory-cache
Though memory caching comes in with it's own set of limitations.
Hope I understood the question correct.

Deploying Node JS application over a server

I have done quite a research of deploying an application over the local server that I have on my machine. Each source code for the Node JS application or the example that is available over the internet specifies to run the application from the console.
Is there any way that i can configure my MAMP server so that when i hit a URL the Node code specified is executed.
Are there any parameters to set for the same ?
I looking forward to the steps to achieve this as i was not able to found a relevant answer for the same as such.

D3 samples in a Microsoft Stack

We're trying to get familiar with D3 (http://d3js.org/), in particular samples such as http://bl.ocks.org/mbostock/3306362 and http://bl.ocks.org/mbostock/2206590. It seems all these samples use local file IO to load geolocation info. The following code snippets are common:
queue()
.defer(d3.json, "/mbostock/raw/4090846/us.json")
.defer(d3.tsv, "unemployment.tsv")
.await(ready)
while other samples often use this signature to load data:
d3.json("someJSONFile.json", function(error, uk) {
console.log(uk);
});
We've created several local html files to test out the samples, but we're running into security issues. It's apparent the script is accessing a local file, which is really giving us problems in a Microsoft stack (Apple or Linux isn't an option at this time, though we have tried Chrome, with no success). How can we enable the html file or refactor the script to have access to the local files?
You need to host the files through a web server since web browsers restrict what types of files can be accessed locally. The simplest way to do this on a windows machine:
Install python
Navigate to the directory holding your example with cmd.exe. Holding down shift, right clicking on the folder with the example and selecting Open Command Window Here is the easiest way to do this.
On the command prompt, enter python -m SimpleHTTPServer 8000, or python -m http.server 8000, on newer versions to start a web server.
Open a web browser (I would really suggest chrome, the dev tools are way ahead of ff and ie), go to 127.0.0.1:8000. The example should show up.

Categories