How can I use Node.js Offline/locally? - javascript

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.

Related

How to use node.js for an offline application

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.

Where do I put front-end code in my backend project and how/when to run it?

The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately? So the process will look like below
python manage.py runserver
in Python colder and then probably
# in the angular2 folder
npm start
Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?
Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?
Q)The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately?
Both Angular and Python can be run differently as well as together.
You could choose to place the Angular files (which qualify for all practical purposes as public files) in the public (or related folder) depending on which framework you're using - Django, Flask, Web2py or so on.
You can also choose to run them independently as standalone apps.
Depends on your requirement. Honestly, there are so many ways to answer this question.
Q)Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?
If you place everything in your assets folder, then as soon as the home route or any other route is made a request for [from a browser] , the public folder passes on to the browser.
Although I'm not sure if it is the case with server side rendering.
If you're using Angular 1, I do not think it fits server side rendering although you could use some libraries out there.
Q)Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?
All the files in PUBLIC folder on the server are accessible by a browser.
All of your questions seem to essentially ask the same question.
There are many approaches to this problem.
If infrastructure management is difficult for you, than maybe it's easier to place them in the same server. You can create another directory and place your html that is served to browser with your JavaScript code.
In case you have a good pipeline (which I think it pays for it self) than having another server that serves your application is better. You can do more things without affecting your service, like caching etc. And your server that runs your service wont be busy serving assets as well.
I have a case where we run a node server, which serves the html and javascript to our users, because that way we can do server side rendering.enter link description here
The flow of code execution will be this : Once the browser of your user hits the server that is serving html and assets, it will download it locally and it will start with JavaScript execution (Parsing, Compiling and Executing). Your JavaScript app might do some API calls upon initialization or it might not, but your service will be executed only if frontend makes a request.
As for CORS it is irrelevant how you serve them, because you can keep them always in the same domain.

Write PDF files from Web-App to USB-Stick

I am concerned with the feasibility of this:
On a pre-configured machine I will have a Web-Application pre-installed, next to an Apache-Suite. So client and server are the same!
In this Web-Application Users can drag and drop PDF-Files to an USB-Icon.
Then the Web-App should write the dropped PDF to an attached USB-Stick.
I have never done something like this (writing to USB), so I am fairly insecure.
And I am well aware of the browser-restrictions concerning JavaScript and Filesystem-Access, but...
after researching a bit I found out, that there might be some possible and
relevant (I'm a Web-Platform-Guy) solutions to this:
Make a "Chrome App" with USB-Permission (does this really work?)
Use PHP to find the USB and then write to it (how would that work under Windows?)
Use some Flash as middle man (not preferred)
Now I'd like to know:
Has anyone some good experience with before mentioned possibilities?
Has anybody ever done something similar? Did it work? Which path did you choose?
How would I know which drive the USB is mounted, and how would I get sure?
What other possible solutions to this problem are there?
You have a website ('client-side' user interface) and a back-end server ('server-side') running on the same machine. This gives you 2 options:
Client-side: Download a file through the browser via HTTP GET and let the user choose where they save it.
Server-side: Build your USB interactions into the back-end (Node.js) code, as #mcgraphix suggests.
Interacting with the USB on the server-side provides the most flexibility. Furthermore, there are a number of libraries that you can leverage. Head to npmjs.org and consider, among others, the following Node.js server-side packages:
usb-detection
usb
With the server-side approach, initiate a Webservice request when the user completes the drag & drop action on the client, and implement the USB interaction within the server (Express.js or similar) method which services the request.
If the letter of the stick is known then writing a file from PHP will be simple
file_put_contents( 'E:\\folder\\file.pdf', $data );
Update
You can read a list of drives into a dropdown and allow a user to select a default drive to write to
https://stackoverflow.com/a/8210132/696535
Your question is more an architecture question than a code specific question.
Your web app (if you insist on a web app) should have two major components, a server side component that can be given arbitrary commands, and a client side component (javascript using XMLHttpRequest) that can make requests to the server side component to execute said arbitrary commands.
So your server side component, the component that serves your web page should have some server side code that can write your pdf to the file system, it should probably generate the pdf file as well rather than doing that on the web browser.
Which technology you use is up to you, whether that's PHP, .Net, Node.js etc...
The general gist is you want a server side framework that deals with HTTP requests, in your case probably a post request from the client side containing the encoded pdf, and responds accordingly. Bind a particular http route to trigger your save logic.
Your http post request to the server will contain your payload which is the pdf file to a particular path, e.g. http://localhost/savepdf that whichever technology stack http listens to (you'll need to configure that)
Your server side component should read the incoming data, decode it as appropriate then make a file system request to write the received payload to disk.

Access node.js app functions directly from html served statically from that node.js app

OK so I may be asking too much here and/or showing my naivety, but bear with me.
At present I have an html (with js) hosted at A, and node.js app hosted at B. The html/js fetches data from the node app via a XMLHttpRequest, and the node app at B dutifully generates the requested data and sends it to A.
I'm trying to reduce the number of http requests generally, and to streamline the performance generally, and wonder whether it's possible to host the html/js via the node app (via express.static()) at A so that when the html/js requests data from the node server, it's actually requesting data from the same server, and indeed all within the same app (since the node app is generating the data and the node app is also exposing the html/js to a static route).
So is there any way for the js in the html to access the node app functions more directly, i.e. rather than sending an http request to the same node app, just accesses the data-generating function within the node app directly, or at least without using an http request?
I have things set up in my node app so that the html/js can be hosted succesfully via express.static() -- so it's working OK to that extent -- but I just need to know whether it's possible to avoid an http request all the way round a big loop and back to the same node app!
The simple answer is, if A and B are far apart, yes, hosting them on the same server will help.
Serving them from the same application won't help as you'll still need to talk via HTTP.
The question of whether you can remove the HTTP calls from A to B is down to application design. You have a static web app and an API and you're basically thinking of scraping that and making it one application.
There are pros and cons to both but I'll be going down the road of personal opinion if I start listing them.
My vote, don't bother :)
When you serve html and js files by express.static() they are not running in server, but serve from server to browser. And so that js scripts are running from browser. Browser scripts to communicate with server, must use http/https requests or sockets. You can communicate browser scripts from server A with server B (but checkout CORS).

How to make CRUD operations on a remote Mongodb with Nodejs

I recently started to play around with NodeJS - all I know is that it's a server side technology. What I did and want to accomplish are as following:
I have a MongoDB running on a remote server. I am using nodejs mongodb driver, and by simply doing the following I can connect to the database and just lets say create a document:
// main.js
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://remote_url:27017/mymongo', function(err, db) {
var document = {a:"1", b:"2"};
db.collection('collection').insert(document, function(err, records) {
if (err) throw err;
}
}
As you know, the code above requires a console call such: node main.js, however I have a HTML5 frontend with several text fields, and I want to pass the fields to my database with a simple button click event. My questions are:
Is it really stupid if I directly connect to remote mongodb as above? Can I call the script from my HTML page? If I can, then what are the drawbacks compared to redesigning it into a client-server structure?
Finally, I think the right practice to accomplish above is to create an http server with nodejs on the remote server which passes client's requests to the mongodb driver. Am I right?
You could try building a REST API to interact with the MongoDB server(s) using vanilla NodeJS or your choice of quite a few additional frameworks. You might try baucis*.
*Disclaimer: I am the main author of baucis
Is it really stupid if I directly connect to remote mongodb as above?
No, using the native MongoDB driver is pretty standard. However, instead of connecting and then immediately interacting with your database, I'd structure the application so that you connect and then wait for HTTP calls or some other function to interact with the database.
Can I call the script from my HTML page?
Absolutely. In your node.js application, I would build in a web server that listens for certain HTTP calls. In your HTML, provide links or forms to GET, POST, etc. the web server that your application is listening on.
For example, your front-end would look like maybe a <form action="/document/add" method="post">. Then, keep main.js as your back-end code running on node.js, but modify it to listen for a POST call to /document/add. When a call to that URL comes in, run the insert code with the POSTed form data.
You could also create an AJAX solution to listen for form submission and submit the POST in the background, wait for a response, and update the page accordingly.
What are the drawbacks compared to redesigning it into a client-server structure?
Advantages and drawbacks are going to be very specific to the type of application you want to create.
I think the right practice to accomplish above is to create an http server with nodejs on the remote server which passes client's requests to the mongodb driver. Am I right?
You are correct. That is pretty standard practice for using node.js and MongoDB. I'm going to recommend Express for creating your API to interface with the database. It provides features such as URL routing right out of the box. However, you can build your own platform, or use any other one that works for your application/environment.
You should use a REST interface for MongoDB. I like sleepy.mongoose a lot. It runs on python and can take a minute to set up, but is well worth the effort.
Here is a blog by the author which helped get me started.
Here is the Demo App deployed to Heroku,
http://nodejs-crud.herokuapp.com/ and the tutorial link is http://codeforbrowser.com/blog/crud-operations-in-node-js-and-mongodb/

Categories

Resources