Problems directly using PhantomJS in node.js - node.js

I'm attempting to use PhantomJS, and I've installed it via NPM.
I can't seem to run any of the of the examples, in fact I can't even run:
var page = require('webpage').create();
I get the error:
Error: Cannot find module 'webpage'
Is there anything i'm missing? I'm using a few other modules that I've installed via NPM in the same directory with no issues

PhantomJS is not for Node.js. You are likely running the examples through node binary.
Read the Getting Started documentation carefully and you'll see that every single PhantomJS example need to be invoked like:
phantomjs hello.js
Note that there is a bridge between Node.js and PhantomJS. In that case, you need to follow the given examples for that particular bridge (there are a few different ones).

You can use something like this:
var page = new WebPage();
Example of code :
var page = new WebPage();
page.open('http://example.com', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});

Related

Module not found: Error: Can't resolve 'fs' when trying to use a NodeJS library

I initiated a basic ReactJS app using npx create-react-app, then I ejected using npm run eject. Now when I am trying to import the Casual library by import casual from 'casual';, I get the following error:
Compiled with problems:
ERROR in ./node_modules/casual/src/casual.js 3:13-37
Module not found: Error: Can't resolve 'fs'
in '/home/me/project/node_modules/casual/src'
And the code around line number 3 in casual.js looks like this:
var helpers = require('./helpers');
var exists = require('fs').existsSync;
var safe_require = function(filename) {
if (exists(filename + '.js')) {
return require(filename);
}
return {};
};
...
I found answers to similar questions. Those were mainly Node or Angular related. I also tried answers suggesting some changes in webpack config, but no luck.
The reason is Casual doesn't work on the front end. It runs on Node.js only.
You need to install maybe a new package to make things work.
Fs is unavailable on the browser so it won't work. Instead, you should use casual-browserify, it will work on browsers.

npm fast-lorem-ipsum not working in nodejs

`var fastLoremIpsum = require('fast-lorem-ipsum').fastLoremIpsum;
console.log(fastLoremIpsum(10,'c'));`
I was trying to use fast-lorem-ipsum npm package but on executing above code in nodejs file,instead of getting lorem-ipsum text i am getting 'undefined' as console output.
What should i do ?
If you look at the documentation for the package, the function you're looking for should be accessed like this —
var fastLoremIpsum = require('fast-lorem-ipsum').fastLoremIpsum;
console.log(fastLoremIpsum(10,'c'));

phantomjs cannot find module webpage in node's child process

I'm trying to run phantomjs in a node child process. Phantomjs complains it can not find module 'webpage'. Running the script from the cli works fine:
phantomjs script.js
I stripped the problem down to these two files:
main.js:
var script = require('./script');
var cp = require('child_process');
cp.exec('/usr/bin/phantomjs script.js');
script.js
var page = require('webpage').create();
page.open("http://www.google.com", function(status) {
console.log("opened google? ", status);
var title = page.evaluate(function(s) {
return s;
}, 'Hello');
console.log(title);
phantom.exit();
});
Running the following command fails:
node main.js
with error:
module.js:340
throw err;
^
Error: Cannot find module 'webpage'
I've tried to specify the working directory in cp.exec as an option without effect. Is there a way to set the node search path for modules in a global context so it can be found in a new node process? Or am I doing something else wrongly?
PhantomJS is not a node.js module and cannot be directly used from node. I think you understand this, because you try to invoke it via child_process.
The problem is the line var script = require('./script');. As I understand, it is the phantomjs script. Since node.js doesn't have a webpage module, but phantomjs does the require fails and everything with it. Simply remove the line. It doesn't seem like you use it anyway.

How can I use a library that calls xmlhttprequest in node.js?

I would like to run tests of OData interfaces from node.js, using the data.js library. Unfortunately, data.js is intended for use in browsers and uses XMLHttpRequest calls. node.js cannot handle such calls because, I believe, they are implemented in the browser, not in JavaScript. Is there a module that will let me use data.js in node.js?
The usual solutions for XMLHttpRequest are OK when you can call them in your own code, but here I don't want to change data.js, so those options are not open.
Here is a sample of what goes wrong:
var odata = require("./datajs-1.1.0.js");
try{
odata.OData.read(
"http://services.odata.org/Northwind/Northwind.svc/Categories"
);
}
catch(err){
console.log ("Exception in index.js - " + err.name + ": " + err.message);
}
Running node.js index.js:
Exception in index.js - undefined: XMLHttpRequest not supported
The exception may be a result of requiring the datajs library with a file system literal ("./") instead of as a node_module (which would be more along the lines of require("datajs")). The latter normally requires use of npm (it stands for node packaged modules), and you would want to run the following command in your project directory:
npm install datajs
The reference page for the datajs library can be found at https://npmjs.org/package/datajs.
Good Luck!
There is a module for that, npm install xmlhttprequest (or similar). That module has issues with escaping... Or you can use jaydata which just works

Having trouble running Phantomjs + node on Heroku

I've successfully got Phantomjs to work on Heroku but now I'm hitting issues with the phantomjs-node interface for node.js (see https://github.com/sgentle/phantomjs-node).
When I'm attempting to initialize Phantom I'm seeing a 10-15 second delay and then:
> phantom stdout: ReferenceError: Can't find variable: socket
phantom stdout: phantomjs://webpage.evaluate():1
phantomjs://webpage.evaluate():1
phantomjs://webpage.evaluate():1
You can reproduce the problem with the following steps or by pulling down my test app at https://github.com/matellis/phantom-test
git init phantom-test
cd phantom-test
heroku apps:create
# create node app as per Heroku instructions here https://devcenter.heroku.com/articles/nodejs
# copy bin and lib folders from http://phantomjs.googlecode.com/files/phantomjs-1.6.1-linux-x86_64-dynamic.tar.bz2 into root of your new project
# if you don't do this step you'll get an error "phantom stderr: execvp(): No such file or directory"
git add .
git commit -m "init"
git push heroku
Test your app has come up, the third to last line will tell you the URL, it should read like:
http://fathomless-ravine-5563.herokuapp.com deployed to Heroku
If successful you should see Hello World! in your browser.
Now from the same folder as your Heroku application run:
heroku run node
At the node prompt try the following:
phantom = require('phantom');
x = phantom.create();
Wait 10-15 seconds and you should see the error. Nothing works from this point on.
This should output file foo.png:
x = phantom.create(function(ph){ph.createPage(function(page){ page.open('http://bbcnews.com', function(status){ page.render('foo.png', function(result) {ph.exit()}); }); }); });
To validate Phantomjs is working fine on Heroku, try the following using my test project:
>heroku run bash
Running `bash` attached to terminal... up, run.1
~ $ phantomjs test.js http://bbcnews.com foo.png
~ $ ls *.png
foo.png
I cannot reproduce any of these problems locally but there are other issues reported where folks may have hit this issue locally.
The problem seems to originate in shim.js line 1637:
s.on('request', function(req) {
var evil;
evil = "function(){socket.emit('message', " + (JSON.stringify(JSON.stringify(req))) + " + '\\n');}";
return controlPage.evaluate(evil);
});
I've tried variations of versions of node, phantom, etc. with no luck.
I've also tried a custom buildpack that sets the DYLD variable, see http://github.com/tecnh/heroku-buildpack-nodejs with no luck either.
Anyone who has got Phantom + Node playing together nicely on Heroku please let me know. There are several references to this on Stackoverflow but nobody is saying "I got it to work, here's how".
I've never used the phantomjs node module, but I do have an app running both node and phantomjs on Heroku.
You need to use custom buildpacks in order to get this to work. My .buildpacks file looks like
http://github.com/heroku/heroku-buildpack-nodejs.git
http://github.com/stomita/heroku-buildpack-phantomjs.git
You should then be able to run phantomjs scripts in a child process:
var script = app.get('root') + '/scripts/rasterize.js' //the phantomjs script to run
, bin = app.get('phantom') //normally this would just be the string "phantomjs"
, spawn = require('child_process').spawn;
// set up args to the phantom cli
// (run the phantomjs command in your terminal to see options/format)
var args = [];
// ...
var phntm = spawn(bin, args);
phntm.stdout.on('data', function (data) { /* do something */ });
phntm.stderr.on('data', function (data) { /* do something */ });
phntm.on('exit', function (code) { /* handle exit */ });
Heroku does not support WebSockets. With Socket.io it has a workaround. Not sure about dnode, which phantomjs-node uses.
I had a problem with WebSockets on Heroku too and I switched to Nodejitsu, which solved it for me.

Resources