Handling .js and .css in Node.js - javascript

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/

Related

protobuf.js using CommonJS?

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>

Looking for a coherent example on how to read a YAML file in a browser. YAML file located on the web server

My setup:
VS Code+ WSL2. Files are all in the same folder (js-ayml.js, the YAML file and the index.html). I run the javascript code by refreshing a page that refers to it. I use the GoLive VS code extension as server
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test js-yaml</title>
<script src="//code.jquery.com/jquery-2.1.0.js">
</script><script src='js-yaml.js'>
</script><script src='readYaml.js'>
</head>
<body>
<h1>Test js-yaml</h1>
<p>https://github.com/nodeca/js-yaml</p>
</body>
</html>
readYaml.js
(function () {
"use strict";
$(document).ready(function () {
$.get('/common/resources/LessonContentsLv01Ln01.yml')
.done(function (data) {
console.log('File load complete');
console.log(jsyaml.load(data));
var jsonString = JSON.stringify(data);
console.log(jsonString);
console.log($.parseJSON(jsonString));
});
});
}());
I have posted this https://stackoverflow.com/questions/70916217/reading-yaml-from-javascript-in-a-browser?noredirect=1#comment125366890_70916217 and it was closed.
I have tried this:
Reading from YAML File in Javascript (Solution 2)
and the example shown here
https://github.com/shockey/js-yaml-browser this says this fork is optimized for browsers
They all fail with the same error
js-yaml.js:9 Uncaught ReferenceError: require is not defined
at js-yaml.js:9:16
That line is var fs = require('fs');
As far as I understand fs is a node.js module and it won't work in the browser
My question is Is there a JavaScript module to open and read YAML files from a web server, a module that works in the browser without any backend?
Note: I am a beginner and I thought this would be a basic example, load a file and parse it.
shockey/js-yaml-browser is broken and hasn't been updated in several years. js-yaml in general has a lot of forks. Manx7/js-yaml works and is reasonably up to date.
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/4.1.0/js-yaml.js"></script>
<script>
// Normally we'd use fetch to get the file. However, stackoverflow
// snippets don't have a way to add another file, so we'll use a
// string instead just to show how the library works.
/*
fetch("sample.yaml")
.then(response => response.text())
.then(text => {
// once the file has been loaded, we can parse it into an object.
const yaml = jsyaml.load(text);
console.log(yaml);
});
*/
const text = `
# Employee records
- martin:
name: Martin D'vloper
job: Developer
skills:
- python
- perl
- pascal
- tabitha:
name: Tabitha Bitumen
job: Developer
skills:
- lisp
- fortran
- erlang
`;
const yaml = jsyaml.load(text);
console.log(yaml);
</script>

How can I read and write into another file using javascript on html website?

I was trying to make a simple website where you can like click on a button and it gets counted, and it should also tell you how often it has been clicked on. I tried using fs for it since I've done something similar with a Discord bot and it worked well. But on the web, it just doesn't.
It looks something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
var fs = require('fs');
var counting = JSON.parse(fs.readFileSync('./Storage/count.json', 'utf8'));
var button = document.getElementById("button");
button.onclick = function() {
counting[count]++;
fs.writeFile('./Storage/count.json', JSON.stringify(counting), (err) => {
if (err) console.error(err);
});
};
</script>
</head>
<body>
<div style="text-align: center">
<button id="button">Increment</button>
</div>
</body>
</html>
(I'm sorry if there are some obvious mistakes, but I'm relatively new to this kind of stuff)
And there is a JSON too of course
{"count":0}
Unfortunately you can't use fs in the browser as it is a node module.
Reference: https://nodejs.org/api/fs.html
One potential route is for you to take your existing node / fs code and move it server side. Then you would just need to develop endpoints for your website to reach.
Otherwise you could try something like localStorage to store the count to the client's browser.
localStorage.setItem('count', 0);
More information: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Unable to establish a neo4j - bolt driver connection in javascript

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

Dynamically get web socket URL

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.

Categories

Resources