require(processing-js) throws Reference Error: Navigator not Found - javascript

I'd like to use processingJS as an npm package in a nodeJS server for deployment on MS Azure. I'm using VS15. I'm having trouble referencing it:
var pjs = require('processing-js');
var http = require('http'),
fs = require('fs');
var port = process.env.port || 1337;
The first line of my code throws
ReferenceError: navigator is not defined
The research I've done leads me to believe that navigator is some property related to the browser but I'm having trouble finding more information.
I have looked at these resources but wasn't able to come up with a solution:
Require('jquery-ui') in node-webkit produces navigator not found error
https://github.com/tobie/ua-parser/issues/440
http://fredkschott.com/post/2014/06/require-and-the-module-system/
I'd like to be able to precompile processing into javascript.
Thanks in advance.

navigator is an object available in a desktop browser by the host environment. (Much like the DOM) -- the javascript language doesn't define the navigator object so V8 (the underlying engine) doesn't provide it and since node isn't a browser, it doesn't implement the navigator object either.
Processing is designed to be used solely in the browser -- either you're going to need to provide a shimmed environment for it in node, or use it in the browser (either headless or not)

For anyone looking back on this question wondering how to precompile processingjs code into javascript code, here was my client-side solution:
var sketch = document.getElementById('processing-canvas');
var processingCode = 'some processingJS code as a string';
var jsCode = Processing.compile(processingCode); // include the processingJS api as well as processingJS in the html page you call this script from
var processingInstance = new Processing(sketch, jsCode);

Related

os.platform returns browser instead of actual OS - React & Electron

I am trying to retrieve the appdata folder location for the application, and since each os has a separate path for the appdata or application support folder, I tried retrieving the os type to specify which path to use. The issue is os.platform() returns 'browser'. I have tried running it on windows and mac, but they all return browser. If i run process.platform in electron.js it gives me the correct os, but in react I get browser. How can I get the proper OS?
In a browser you can use a combination of navigator.platform, navigator.userAgent, and navigator.userAgentData.platform to get the information you want, but it might take some testing and parsing.
AFAIK, navigator.userAgentData.platform is available only on Chrome/Chromium-based browsers, but gives the most straight-forward result when available.
Checking which platform you're using, rather than checking for specific features, is generally consider not to be a good idea -- but I've found it hard to avoid sometimes myself, especially when working around platform-specific quirks and bugs.
This is because you are running process.platform in the renderer process.
In order to get the correct value you need to run platform.process either on main process (usually the background.js file) or via #electron/remote, like this:
window.require('#electron/remote').process.platform
#electron/remote's usage depends on your electron version, I recommend you to check #electron/remote readme.
Have you tried using Electron's app.getPath(name) method?
This method will return the users application data directory.
Only once the app is "ready" can you retrieve this path.
// Electron module(s).
const electronApp = require('electron').app;
// Application is now ready to start.
electronApp.on('ready', () => {
// Get the users app data directory.
let appData = electronApp.getPath('appData');
// Get the users home directory.
let home = electronApp.getPath('home');
})

Reference Error: self is not defined

We are facing the issue
"Reference Error: self is not defined'
while trying to use React-data-grid. The issue is on the server side while trying to build the nodejs application using webpack. We are facing issue in the generated bundle file in the following lines
isOldIE = memoize(function() { return /msie
[6-9]\b/.test(self.navigator.userAgent.toLowerCase()); }),
Could you let us know how can we fix this. It looks like the react data grid package has issues with the server side rendering.
self is likely referring to window which is not available on the server side...it's only available in a browser context. The navigator reference makes this especially apparent. This code is trying to test the user agent for Internet Explorer verison.
self.navigator.userAgent.toLowerCase()
As Jordan pointed out, there is an open issue #361 regarding isomorphic rendering.
If possible, try to avoid executing that code when on the server-side. Otherwise, you'll have to wait for a patch in react-data-grid.
Fixed it by using the following package exenv which restricts it check for the posted condition only during client rendering
var ExecutionEnvironment = require('exenv');
if(ExecutionEnvironment.canUseDOM) {
const ReactDataGrid = require('react-data-grid');
const {Toolbar, Filters: {NumericFilter, AutoCompleteFilter, MultiSelectFilter, SingleSelectFilter}, Data: {Selectors}} = require('react-data-grid-addons');
}

What native javascript method is capable of creating a server?

I am new to nodejs. I have successfully installed it on my computer (and rebooted). I have created a hello_world.js inside My Documents directory (I'm on a windows xp computer):
console.log("hello world");
var my_http = require( 'http' );
var my_server = my_http.createServer( ... ) ;
...
I have successfully opened a windows command prompt, cd'd to the My Documents directory, executed the .js file, and received 'hello world' output. And I have navigated my browser to the running localhost port (for my experiment: http://localhost:1337/)
But I have 2 major questions based on this:
1 - where is 'http' ... I suppose it is a module(?), but I do not find such a directory within my nodejs installation directory.
2 - how does the http method, createServer, actually create a server? Does native javascript have such a method?
The node.js standard library is written in Javascript and C++, and C++ modules can be loaded in js code via process.binding. Specifically for http.createServer, it's a wrapper around _http_server.Server, which invokes net.Server, which uses the C++ TCP wrapper .
See here for more details.
To answer the second question, createServer just creates and populates the control object, the actual work is in listen, which first creates a handle and this is where C++ code is actually called for the first time.
1) http is a built-in node module. You can read up on the documentation for it here: https://nodejs.org/api/http.html. Node provides a lot of modules out of the box to assist w/ everyday operations (interacting w/ file systems, making HTTP requests, creating servers, working with paths, etc.)
2) Not sure what you mean by "native" JavaScript. JavaScript is just a language. I think you're really asking about the runtime environment. If you are using JavaScript in the browser, then no you can't start an HTTP server. But Node.js runs on the server, so in this environment it can do all sorts of stuff that you can't do w/ JavaScript in the browser, such as access the file system.

Write a variable to a file in Javascript

This may be a copy.. but I'm not getting the thing I want from the answers I saw..
I just want to save a particular variable into a local file using Javascript. I know how to read a file.
I wrote this code..
<script>
var fs = require('fs');
fs.writeFile('http://localhost/online/hello.txt', 'Hello Node', function (err) {
if (err) throw err;
else
{
console.log('It\'s saved!');
}
});
</script>
What is the error here.. or is there a simple and straight-forward way of doing it..??
It seems you're trying to call node-js code from the browser. Although javascript can run in both the browser and on the server (node-js), those are separate systems.
Another thing you can do is google "HTML save file example" and see how this is typically implemented - by opening a save dialog for the user, getting his/her permission, etc. (otherwise any website could just write any file to your computer...).
You are writing NodeJS code for client side application. You must understand the difference between javascript on browser and javascript on NodeJS platform.
Javascript is a language just like C, Java and Python
V8 is a javascript engine to run the javascript application. It is something similar to JRE for Java.
Browser(Only Chrome) uses V8 engine for running javascript application. Other browsers use different javascript engine. Five years ago, there was only one possibility that javascript can only work on browser. You cannot use javascript for application programming like C and Java
NodeJS is a platform which uses V8 to enables developer to write javascript application just like C, Java program. NodeJS also has some inbuilt library for accessing file system,
networks, and much more utilities. One of the internal library in NodeJS is fs. It only works on NodeJS application, not on browser application.
This can be done pretty simply using jrpc-oo. jrpc-oo links the browser and nodejs using the JRPC2 protocol. jrpc-oo abstracts classes over JRPC so that either side (nodejs or the browser) can call eachother.
I have setup an example repo to do exactly this here. Use the writeToFile baranch. I will break out the important parts here.
First in nodejs, we write a class with a method to write input arguments to file. The method looks like so (from the file TestClass.js) :
const fs = require('fs');
class TestClass {
writeToFile(arg){
fs.writeFileSync('/tmp/browser.json',JSON.stringify(arg));
}
}
In the browser we inherit from the jrpc-oo class JRPCClient and call the server class TestClass and method writeToFile like so (from the file src/LitJRPC.js) :
import {JRPCClient} from '#flatmax/jrpc-oo/jrpc-client.js';
export class LitJRPC extends JRPCClient {
writeObjToFile(){
// create the argument we want to save to file
let dat={name:'var',value:10};
// Ask the server to execute TestClass.writeToFile with args dat
this.server['TestClass.writeToFile'](dat);
}
}
Finally we run the nodejs app and the web-dev-server and we look at the browser console and nodejs console to see what happened. You will see the browser variable dat saved to the file /tmp/browser.json
As we are using a secure websocket for jrpc, you will need to generate the certificate and clear the certificate with the browser before the app will work. If you don't want to worry about security then don't use secure websockets. Read the readme in the reference repo for more information on setup and usage.

Can I/how can I translate a Selenium webdriver test script from node.js over to phantomjs - ghostdriver?

I recently began working with Selenium and to make life easier to start I was using node to run my scripts so that I could visually monitor the tests. My challenge now is to convert it so that it can be run as a headless test. Unfortunately, most of the resources that I have come across only address using phantomjs and ghostdriver with Java or Python. My boss wants me to run the test through phantomjs without Java or Python. Eventually these tests will be run remotely through a Linux VM on a server without a GUI. Currently I am testing using Mac OS X 10.8 and still have many bridges to cross in order to get to my goal.
My most important question firstly, is it possible to run a script from phantomjs through a port without the use of Java or Python? I have spent hours poring through as many resources as I could come across and I've come up with no solution.
If so, how can I properly initialize the test to run headless? Here is how I scripted the start of my functioning test. I want to properly switch the capabilities from firefox to phantomjs and be able to run it headless using the appropriate port. The rest of the test navigates to a specific site, logs in through a widget, then does further navigation to the area which I will build further tests on which to manipulate after I get this working.
var webdriver = require('selenium-webdriver'),
SeleniumServer = require('selenium-webdriver/remote').SeleniumServer;
var server = new SeleniumServer("Path/selenium-server-standalone-2.39.0.jar", {
port: 8910
});
server.start();
var driver = new webdriver.Builder().
usingServer(server.address()).
withCapabilities(webdriver.Capabilities.firefox()).
build();
The test works perfectly, but I am new to this so there might be something foolish that I am overlooking. Please let me know what adjustments to make so that it will run headless through phantom. When I attempt to use node to run the script after switching capabilities to phantomjs it produces
"/Selenium/node_modules/selenium-webdriver/phantomjs.js:22
LogLevel = webdriver.logging.LevelName,
^
TypeError: Cannot read property 'LevelName' of undefined
at Object.<anonymous> (/Selenium/node_modules/selenium-webdriver/phantomjs.js:22:33)
That's a read only file that I can't adjust, any attempts that I made to define "LogLevel" or "LevelName" to the appropriate corresponding value (DEBUG, etc.) were fruitless.
And if I run it through phantomjs itself I get -
"Error: Cannot find module 'path'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require"
(It also lists module 'http') -- (and various undefined function errors)
I feel that with that instance I didn't properly organize where the files for Selenium, phantomjs, and ghostdriver should go in order to play nice. I also removed the server setup portion and instead ran this first, then the script separately.
phantomjs --webdriver=8910
But it yielded the same result. All of my research to fix these issues turned up instructions for Java and Python but not Javascript by itself. Rather than chase through many rabbit holes I figured it wise to consult better minds.
If you know better than I do and that it is fruitless to attempt this without Java or Python, please let me know. If you know where the issue lies within my script and could propose a fix please let me know. I hope that I have properly described the nature of my issue and if you need more information I will do my best to provide it to you.
This is my second week working with Javascript so if you believe I am making a noob error you very well may be correct. Please, keep in mind that the script works through node with selenium webdriver.
Many thanks for your time!!!
~Isaac
This was a bit tricky but here is the solution I've pieced together:
var webdriver = require('selenium-webdriver'),
SeleniumServer = require('selenium-webdriver/remote').SeleniumServer,
server = new SeleniumServer('/path/to/selenium/selenium-server-standalone-2.41.0.jar', {
port: 4444
}),
capabilities = webdriver.Capabilities.phantomjs();
capabilities.set('phantomjs.binary.path', 'path/to/phantom/bin/phantomjs');
var promise = server.start().then(function() {
var client = new webdriver.Builder().
usingServer(server.address()).withCapabilities(
capabilities
).build();
return {
'client': client,
'server': server
};
}, function(err) {
console.log('error starting server', err);
});
You can then use the promise with selenium's mocha-compatible test framework to hold the test till the server has started.
I found the documentation really helpful once i figured out the navigation is on the far right of the page. Here's the URL: http://selenium.googlecode.com/git/docs/api/javascript/module_selenium-webdriver.html
Then you'll be stuck where I am. Getting selenium-webdriver to quiet down.

Categories

Resources