I am relatively new to JS but very familiar with protobuf. I'm currently designing a web page hosted from a Java HTTP server, and would like to implement protobuf communication between them.
My issue is on the browser side. After some research I found the protobuf.js git page and attempted to use this within my javascript. I ran into issues firstly getting the module over HTTP because
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.js"></script>
uses text/plaintext and fails to return. Adding a type=text/javascript just led to protobuf is not defined.
I then tried to take the project source into my web root, and directly use this:
<script type="text/javascript" src="./js/protobuf-js/src/index.js" ></script>
and:
import * as protobuf from "./js/protobuf-js/src/index.js";
This worked and the web server returned the file. Now, this is where my understanding reaches it's limits. From what I can tell from the README page on git, it distinctly says
"The library supports CommonJS and AMD loaders and also exports globally as protobuf."
If I look inside index.js I see the following:
var protobuf = module.exports = require("./index-light");
which throws a Module is not defined in ES module scope exception in browser.
Nowhere else online could I find working examples of the protobuf.js being used in commonJS as it states in the git, it all refers to Node.js which I don't want to use as i'm using Java for the webserver side of things.
Am i being really dumb and missing something obvious?
Thanks
There are example in https://github.com/protobufjs/protobuf.js.
a small example:
hello.proto
syntax = "proto3";
message Test{
string msg=1;
}
test.html
<html lang="en">
<head>
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.11.3/dist/protobuf.js"></script>
</head>
<body>
<script>
function test(){
protobuf.load("hello.proto", function(err, root) {
var TestMsg = root.lookup('Test');
var payload = {msg:'hello'};
var result = TestMsg.verify(payload);
if(result) throw Error(result);
var msg = TestMsg.create(payload);
var binMsg = TestMsg.encode(msg).finish(); // this is the binary protobuf message
// to handle blob data from server via websocket, you need handle like below
// event.data.arrayBuffer().then(buf =>{
// var msg = TestMsg.decode(new Uint8Array(buf));
// }
// deserialize
var msg2 = TestMsg.decode((binMsg));
console.log(msg2.toJSON());
alert(msg2.msg);
});
}
</script>
<input type="button" value="test" onclick="test()">
</body>
</html>
Related
I am trying to create a connection between my html embedded javascript and my neo4j database by running the index.html in Chrome. I have reduced the source of the problem to 'neo4j' not being recognised. So the error thrown will be of the type:
Cannot read property ['driver'/'basic'/etc...] of undefined.
In this case I have assumed that 'undefined' is referring to 'neo4j', which would mean that I am not implementing 'neo4j-web.min.js' correctly.
The below block of code is extracted from my index.html and has been taken from: https://www.npmjs.com/package/neo4j-driver
<script src="node_modules/neo4j-driver/lib/browser/neo4j-web.min.js"></script>
<script type="text/javascript" charset="utf-8">
var driver = neo4j.driver("bolt://localhost:7474", neo4j.auth.basic(neo4j,
neo4j));
</script>
Given that the issue seems very localised to this code, I spared everyone the rest of the document. If further context is missing, I'd be happy to provide it.
The neo4j-driver module uses an odd system whereby you have to specify which version of the API you want to use.
<script src="node_modules/neo4j-driver/lib/browser/neo4j-web.min.js"></script>
<script type="text/javascript" charset="utf-8">
neo4j = neo4j.v1
var driver = neo4j.driver("bolt://localhost:7474", neo4j.auth.basic(neo4j,
neo4j));
</script>
I agree with #varbrad
My 2cts: check the servername
You are using the alias localhost
I have a Play 2.5 application that uses a web socket. In my Controller I establish it as
def socket = WebSocket.accept[JsValue, JsValue] { request =>
ActorFlow.actorRef(out => TroiWebSocket.props(db, out, comm.communicator, system))
}
And, it's accessed in my routes as
GET /push-notifications controllers.Application.socket
As, currently, my application is running locally, I can reference the socket in a javascript file using
var socket = new WebSocket("ws://localhost:9000/push-notifications");
However, I'm starting to move my stuff away from the localhost, and need a way to reference the url in my javascript file. This URL might change (and could be different depending on the development environment). So, how can I reference this URL dynamically? That is, how do I say
var socket = new Websocket(URL_OF_WEBSOCKET)
I thought of breaking it up in my config files and trying to do it that way, but I'm not so sure that would work.
Any and all help would be appreciated.
If you are using plain javascript. Declare a File config.js and define some global Object with some config data.
<html>
<head>
<script>
var config = {
"localWSUrl" : "ws://localhost:9000/socket",
"wsUrl" : "ws://serverurl.com:443/socket"
}
</script>
<script>
console.log(config.wsUrl);
</script>
</head>
<body>
</body>
</html>
For simplicity sake I wrote everything in one file. You would exclude the config part and import the file via the script tag's src attribute. And then you can reuse it where you need it.
If the URL to get main page of your application is the same or partially same to connect websocket, suppose:
Url app: myapp.com
Websocket url: myapp.com/push-notification
So you could do in your js file using window.location of js standard api
var tcp = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
var host = window.location.host;
var path = '/push-notification';
var ws = new WebSocket(tcp+host+path);
Something like that..
I hope It helps.
I have the following Thrift client code in javascript:
<script language="javascript" type="text/javascript" src="thrift.js" />
<script language="javascript" type="text/javascript" src="QuantSvc_types.js" />
<script language="javascript" type="text/javascript" src="QuantSvc.js" />
<script language="javascript" type="text/javascript">
function calc() {
var transport = new Thrift.Transport("http://localhost:9997/QuantSvc/");
var protocol = new Thrift.Protocol(transport);
var client = new QuantSvcClient(protocol);
try {
result = client.ListAllVariables()
} catch(ouch) {
alert("An exception occurred!")
}
}
</script>
Which is triggered when I push a button on my HTML page. Then, I have the following server-side Scala code, running on localhost:9997:
object Application extends App {
val handler = new QuantSvcHandler()
val processor = new QuantSvc.Processor(handler)
val serverTransport = new TServerSocket(9997)
val server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor))
}
Where the QuantSvcHandler's ListAllVariables function is (basically a skeleton function, just trying to get things to work):
override def ListAllVariables(): util.List[Attributes] =
{
var input = scala.collection.mutable.Buffer[Attributes]()
input
}
I put a breakpoint at the first line of ListAllVariables, and also a few places in the QuantSvcHandler processor. I run the server in debug in intellij IDEA, open my HTML page in Chrome, and push the button (the one that calls the javascript calc() function). The button stays stuck and I see no kind of response on the server, the breakpoints aren't being hit.
Any ideas about what I'm doing wrong?
You mix a HTTP client with a socket server.
Although HTTP uses sockets, the Thrift HTTP transport is not compatible with the Thrift Sockets transport. You need to set up the exact same protocol/transport stack on both ends. The only exception to that rule is that some server transports implicitly require an additional framed transport layer on the client side.
So the solution is to use a HTTP server. Depending on the version you use, you may also have to switch to the JSON protocol.
I want to make a JQuery routine that can write information (append) to a text file that either exists or does not exists. If the file does not exists than it should create the file and if it does it should either append or start writing new data to the file. I think append would be the best choice for a file logger. So it must append the data to the file.
I found this code on the internet and am trying to work it around so that I can use it on my page to write information to a simple text file.
Question: How can I make the following code log to a file for download?
Below is the new code and how I read the page that was listed in the comments on how a logger in Java script should work. The code is not working and I am not really certain as to why.
I am not really certain as to how the download works either but if I can just get the logger to work I will be happy for the time being.
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
<script src="log4moz.js">
</head>
<script>
getLocalDirectory : function() {
let directoryService = Cc["#mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
// this is a reference to the profile dir (ProfD) now.
let localDir = directoryService.get("ProfD", Ci.nsIFile);
localDir.append("XULSchool");
if (!localDir.exists() || !localDir.isDirectory()) {
// read and write permissions to owner and group, read-only for others.
localDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
}
let myFile = XULSchool.getLocalDirectory();
myFile.append("someFile.txt");
let formatter = new Log4Moz.BasicFormatter();
let root = Log4Moz.repository.rootLogger;
let logFile = this.getLocalDirectory(); // remember this?
let appender;
logFile.append("log.txt");
root.level = Log4Moz.Level["All"];
appender = new Log4Moz.RotatingFileAppender(logFile, formatter);
appender.level = Log4Moz.Level["All"];
root.addAppender(appender);
this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject");
this._logger.level = Log4Moz.Level["All"];
this._logger.fatal("This is a fatal message.");
this._logger.error("This is an error message.");
this._logger.warn("This is a warning message.");
this._logger.info("This is an info message.");
this._logger.config("This is a config message.");
this._logger.debug("This is a debug message.");
this._logger.trace("This is a trace message.");
</script>
<body>
<form id="addnew">
<input type="text" class="A">
<input type="text" class="B">
<input type="submit" value="Add">
</form>
</body>
</html>
#Smeegs says this nicely
Imagine a world where any website can edit files on your computer
JavaScript (or jQuery) cannot touch the user's file system.
Even if you find some hacked up thing that works via ActiveXObject, you should not attempt to do this. Cross-browser support would be very narrow for this feature.
If you want to write out file, just provide the user with a download.
If this is just a means of reading/writing some kind of data, look into localstorage.
I'm trying to create a simple chat application with node.js and jQuery but I'm getting an error in my console saying '$ is not defined'. I'm following a tutorial where the authr is using jquery without a problem.
My chat.js (the server):
var http = require('http'),
sys = require('sys'),
fs = require('fs'),
ws = require('./ws.js');
var clients = [];
http.createServer(function(req,res){
res.writeHead(200,{
'Content-Type': 'text/html'
});
var rs = fs.createReadStream(__dirname + '/test.html');
sys.pump(rs, res);
}).listen(4000);
ws.createServer(function(websocket){
websocket.on('connect', function(resource){
clients.push(websockets);
websocket.write('Welcome');
});
websocket.on('data', function(data){
clients.forEach(function(client){
client.write(data);
});
});
websocket.on('close',function(){
var pos = clients.indexOf(websocket);
if(pos >= 0){
clients.splice(pos, 1);
}
});
}).listen(8081);
test.html (the client):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
ws = new WebSocket("ws://localhost:8080");
ws.onmessage = function(event){
var data = data.replace(/&/g, "&").replace(/</g,"<").replace(/>/g,">");
$('#log ul').append('<li>' + data + '</li>');
}
});
</script>
</head>
<body>
<div id="log"><ul></ul></div>
<div id="console">
<input type="text" id="entry"/>
</div>
</div>
</body>
</html>
I was getting errors before I stripped out all the .css and other .js src so I'm pretty sure the problem is with the 'Content-Type' code in the server.
I suspect the problem is that you are not serving jquery-1.7.2.min.js from your server, so the web page is not loading jquery, hence no $. First, try referencing a hosted jquery and see if that fixes your problem.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Although not totally relevant to your problem, if you are building a public website, then it is generally a good idea to reference hosted jquery (and other libs) as your users will probably have a locally cached copy already (thanks to other sites which did the same thing). See http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/ for a reasonable explanation of this.
Generally, though, you are going to want to serve some static files: your own css and js, images and the like. There are --plenty--of--posts-- describing how to do this longhand with node, but you may want to look at a dedicated module like this: https://github.com/cloudhead/node-static
On the server side, the code you are using is very old. sys.pump has been deprecated for at least over a year.
I'd advise you to read the examples from socket.io. There happens to be a chat server as well in the examples.
Who's serving your static files? From the code you have, it looks like the only static file you're serving is the HTML page.
You need to add some code to handle all static files at a specific location. Basically, you need to handle all static files within your
http.createServer(function() {...})
See: http://www.sitepoint.com/serving-static-files-with-node-js/