How to use node.js for an offline application - javascript

I don't really understand some aspects of Node.js. I'm working on a Project for which I need a fast and modern looking UI, therefore I'm using JavaScript with React. Additionally, I need to access a seral port on my PC so I decided to use Node.js. Everything will happen offline. I just want to read my serial port, process the data and display it on an UI. So, I managed to write a simple script which just outputs a string with console.log(). When executing node script.js everything works as expected. But as soon as I want to run anything which needs a GUI, thats not possible anymore (of course, since I'm working in the terminal). So, as far as I'm understanding node, I have to set up a http server and access it in my browser. At this point I don't really understand why node.js is neccessary, because then the script is executed by the browser (or is it?). I know that's not really a question, but I am quite confused about this and wanted to know if that's the right way to use node.js for an offline application.

At this point I don't really understand why node.js is neccessary, because then the script is executed by the browser (or is it?).
It isn't.
Node.js runs an HTTP server.
The browser makes an HTTP request to that HTTP server.
Node.js executes code to determine what response to make to the browser.
The code to access the serial port would be part of that code which is used to determine the response. This has to run via Node.js because browsers don't provide any API that would make direct access to a serial port possible.
You might want to look at Electron.js which bundles Node.js and the Chromium browser together for a more traditional-seeming GUI application (without the usual trappings of a browser like the address bar).

Browser environments can't (yet) read from a serial port. So, your Node.js application is required to proxy data from the serial port to your web-based application.
Otherwise, you could create a progressive web app (PWA) and not need Node.

Related

How can I use Node.js Offline/locally?

Maybe i'm misunderstanding how Node.js works but, I would like to use it just as a server backend for a web app, without it running as a service/listening a port.
I'm willing to hear ideas to better solve the issue, this app will only be available on our intranet.
Example of what i'm thinking :
backend server.js :
function connectDb(usr, pwrd){
//Some npm package code to connect to a db
return console.log("Sucessfully connected")
}
frontend javascript.js :
require("server.js")
$(".connect.button").on("click", function(e){
connectDb($(".connect.user").text(), $(".connect.pwrd").text())
})
There are two different aspects with your question and code example on which you could work to get a better understanding of the ecosystem.
Client / Server
When a client wants to get some resource from a server, it connects to a specific port on that server, on which the back-end application is "listening". That means, to be able to serve resources coming from a database, you must have a Node process listening to a port, fetching the requested resources from the database, and returning them. The perfect format for that kind of data exchange is JSON.
To get a better understanding of this process, you may want to try and write a simple Node app sending a piece of JSON over the network when it receives a request, and try to load it with an XHR in client code (for example with JQuery's AJAX method). Then, try and serve a dynamic piece of JSON coming from a database, with a query based on the request's content.
Module loading
require("server.js") only works in Node, and can't be used in JavaScript that is running in a client's browser (Well, at least for now. Maybe some kind of module loading could be normalised for browsers, but that's another debate.).
To use a script in a client browser, you have to include it in the loaded page with a <script> tag.
In node, you can load a script file with require. However, said script must declare what functions or variables are exposed to the scripts that require it. To achieve it, you must export these variables or function setting module.exports.
See this article to get some basic understanding, and this part of Node docs to master all the details of module loading. This is quite important, as this will help you structure your app and avoid strange bugs.
For one thing, node itself isn't a web server: it's a JS interpreter, which (among other things) can be used to write a web server. But node itself isn't a web server any more than Java is.
But if you want things to be able to connect to your node program, in order to do things like access a database, or serve a webpage, then, yeah, your program needs to be listening on some port on the machine it's running on.
Simply having your node program listening to a specific port on your machine doesn't mean that anyone else can access it; but that's really a networking question not a programming question.

Execute Nodejs script from html file

I want to execute a nodejs script from a html file.
I'm trying browserify but i'm getting many errors like "http.createServer is not a function".
Is there any alternatives to browserify?
No alternative to browserify is going to let you do things which are simply impossible in a browser environment … including starting an HTTP server.
You cannot execute node.js scripts on the client side.
Actually, that statement isn't entirely true. If a script contains only code that both the browser and node.js can run, or can somehow detect which environment it's running in and switch over to code friendly to that environment, then it will work. But a script is limited to the capabilities of the environment it's running in, so calls like http.createServer() will not function in the browser. It's not defined in the browser, and probably never will be. That's too dangerous from a security perspective.
What you can do is create a server-side API in node.js, and have the browser call it through AJAX. The script serving up your API will be running in node.js, so it can do anything that node.js can do. However, because that code isn't running in the browser, it won't be able to affect the browser, except by whatever it returns.
I suspect that you actually need two scripts -one on the server and one on the client- that communicate with each other. How you set up that communication is up to you, but if you're going to be starting servers in response to AJAX calls, then you're going to need to be very careful about security. Still, this is doable; apps like webmin are common.
Starting a server on browser won't be possible.
No sane browser would allow that as it can lead to drastic security loophole and attacks.

Is there a browser-based Websocket listener implementation?

I am interested to know if anyone has built a javascript websocket listener for a browser. Basically the server side of a websocket that runs in a client. This would allow messages to be sent to the client directly. Why? Because instead of having a Node.js, python, java, etc, server process sitting on or near the client/browser, I can just use a thread in the browser as a listening server thread. I don't think that any browsers support this currently.
I've run across answers like this: https://news.ycombinator.com/item?id=2316132
Just curious if anyone has done this. I believe that the current Websockets spec does not support listeners on the browser. It would make the deployment of various peer-to-peer applications a bit easier to deploy.
WebRTC allows for peer-to-peer connections to be made between browsers.
You would still need a server in order for individual users to discover each other but then they could connect directly to each other rather than having to pass all their traffic via a central server.
The idea.
You can use a simple echo server written in any language. Your script can send the data to the server then get it back, handle it on the same page with different functions/classes emulating the real server.
An example: http://www.websocket.org/echo.html
Then, you can think about different formats of packets to/from server to diffirentiate them inside one script.

Node.js chat without Socket.IO

I just started learning Node.js and as I was learning about the fs.watchFile() method, I was wondering if a chat website could be efficiently built with it (and fs.writeFile()), against for example Socket.IO which is stable, but I believe not 100% stable (several fallbacks, including flash).
Using fs.watchFile could perhaps also be used to keep histories of the chats quite simply (as JSON would be used on the spot).
The chat files could be formatted in JSON in such a way that only the last chatter's message is brought up to the DOM (or whatever to make it efficient to 'fetch' messages when the file gets updated).
I haven't tried it yet as I still need to learn more about Node, and even more to be able to compare it with Socket.IO, but what's your opinion about it? Could it be an efficient/stable way of doing chats?
fs.watchFile() can be used to watch changes to the file in the local filesystem (on the server). This will not solve your need to update all clients chat messages in their browsers. You'll still need web sockets, AJAX or Flash for that (or socket.io, which handles all of those).
What you could typically do in the client is to try to use Web Sockets. If browser does not support them, try to use XMLHttpRequest. If that fails, fallback to Flash. It's a lot of programming to do, and it has to be handled by node.js server as well. Socket.io does that for you.
Also, socket.io is pretty stable. Fallback to Flash is not due to it's instability but due to lack of browser support for better solutions (like Web Sockets).
Storing chat files in flatfile JSON is not a good idea, because if you are going to manipulating the files, you would have to parse and serialize entire JSON objects, which would become very slow as the size of the JSON object increased. The watch methods for the filesystem module also don't work on all operating systems.
You also can't compare Node.js to Socket.IO because they are entirely different things. Socket.IO is a Node module for realtime transport between the browser and the server. What you need is dependent on what you're doing. If you need chat history, then you should be using a database such as MongoDB or MySQL. Watching files for changes is not an efficient way and you should just send messages as they received.
In conclusion no, using fs.watchFile() and fs.writeFile() is a very bad idea, because race conditions would occur due to concurrent file writes, besides that fs.watchFile() uses polling to check if a file has changed. You should instead use Socket.IO and push messages to other clients / store them in a database as they are received.
You can use long pooling method using javascript setTimeout and setInterval
long pooling
basically long pooling working on Ajax reqest and server responce time.
server will respond after a certain time (like after 50 seconds ) if there is not notification or message else it will respond with data and from client side when client gets response client javascript makes another request for new update and wait till response this process is endless until server is running

Can you have a Socket.IO (express) server be loaded from a web browser?

You know, a web server. Right now my Socket.IO server loads from a BATCH file that is a JavaScript file. Can you use node and make the socket.io server load from a web browser. Like a web-server utility tool or something of the sort.
That's explicitly not possible due to the design of WebSockets. It starts as a special HTTP request that, after the handshaking, drops the HTTP protocol and strips it down into the WebSocket protocol -- a nearly bare protocol similar to (but slightly more managed than) raw TCP. Because a web browser specifically cannot handle HTTP requests, it could never initiate the socket as a server.
This was done specifically so it wouldn't be possible to write a drive-by botnet website to use scores of users' computers for DDOS attacks without their knowing, amongst other security concerns.
So it wouldn't surprise me if Flash supported that kind of behavior. ;) (I know Java can, but who enables Java applets?)
I'd say you Can. Not that I can think of a good use case.
You would need to put the startup code somewhere where the web server could run it and you would need to get the web server to return some information to the browser to allow it to then connect. You would also have to insert the socket.io code into the browser after the socket server had started.
So I Think that it would indeed be possible but rather complex for little gain. I suppose one possible use case would be to restart a socket server after failure. Actually I'd do that a slightly different way, probably by calling an external script from Node.
fortunatly the answer is no. if you mean by load / launched , NO. but you can create a script on a server that launch another server once a url is requested by a a client.

Categories

Resources