Modifying HTML Website from Node.js Server to Display File Data - javascript

So. I'm a total noob. And most of my question is geared towards just not understanding data transfer or Web servers properly.
Anyway, I am creating a project which hosts a very simple and lightweight Node.js server. In this server, I need to create a website to be able to view file data which resides on the server. On the server, I have a directory listing that goes something like this...
- info
--- client_IPAddress1
------ dataFile1.info
------ dataFile2.info
------ dataFile3.info
--client_IPAddress2
------ dataFile1.info
------ dataFile2.info
------ dataFile3.info
--client_IPAddress3
------ dataFile1.info
------ dataFile2.info
------ dataFile3.info
On the node server, I need to be able to read this file data, and modifying a table element on an html page to display the contents of the files. So far, all I know how to do is display the html page directly like this...
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Context-Type": "text/html"});
fs.createReadStream("clientMonitor.html").pipe(response);
Now, I have a button like so...
<div class="refresh-btn" href="http://169.254.0.4:8888/client-data">
<p><b>Refresh</b></p>
</div>
Which I want to be able to refresh that data to display to a table element. So, on the node.js server what do I do here?
}else if(request.method == 'GET' && request.url == "/client-data"){
//TODO
}
I am a complete and total stranger to node.js. A quick solution or a link to a helpful website, or simple a link to a tutorial about data handling that covers topics akin to these would be extremely helpful. I am running this on a Raspberry Pi using Rasbian Jessie. If anyone knows another solution that they could point me for this platform, again, it would help.

Not sure what the output needs to be following your example, but I would surly start by using express.js in your project. This will simplify greatly your RESTfull api.
Depending on how noob, you are to node, I will try to guide you thru the simplest way I can! ;)
You first need to install Express in your node project.
From the command shell you type npm install express --save to install the node_module. The --save adds the dependency to your package.json. (Depending on your user's role, you might have to use the sudo command (sudo npm install express --save)
Using the following link Express "Hello World" example you will find the simplest example on how to use Express.
So if we use your example your setting might look like this.
var express = require('express')
var app = express()
app.get('/', function(req, res){
res.sendFile(__dirname + '/clientMonitor.html');
});
app.get('/client-data', function(req, res){
/* Depending on what you use on your client side,
you may get data here than send a response in json or flat data.*/
res.json(aJsonObject); // For json response {"Context-Type": "application/json"}
// OR
res.send('AnyValue'); // Will send 200, {"Context-Type": "text/html"}
// OR
res.sendFile(__dirname + '/someFile.html');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!')
})
For your client side, you may use any plugin such as DataTables.net or custom-made function that updates your data in your table using Ajax calls to refresh the information.
Hope this will help solve your issue!
If you decide to use POST instead of get, you will do something like :
app.post('/client-data', function(req, res){
var data = req.body.data;
}
Or if you wish to use queryStrings in the Get url parameters, you will do soemthing like :
app.get('/client-data/:id', function(req, res){
var data = req.params.id;
}

Related

Access a local directory to retrieve files from localhost and write back

I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.
You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");
app.get('/myFile', (req, res) => {
var filepath = __dirname + '/myfiles/thefile.json';
var file = fs.readFileSync(filepath, encoding);
res.json(JSON.parse(file));
});
Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });
ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.

Route file failing to update in Express.js

I am new to using both Node and Express.
Express.js looked great, so I created a local deployment of a vanilla install.
Visiting http://localhost:3000/users prints the expected message:
respond with a resource
I try changing the text to this instead:
respond with no resource
But the change is not made. This is the contents of users.js, almost exactly the same as default:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with no resource');
});
module.exports = router;
And here is a screenshot. Top left is the above code. Bottom left demonstrates a grep for "respond with a resource" failing to produce any results. The right hand side is my browser displaying old data.
What am I doing wrong that the data is not updating?
Your application will not automatically update if you use node <path/to/main>.js to run your application. node will run your application in the form it was when initially started, until that process is terminated.
The most common way to address this is by using a process manager, the most popular one used during development is nodemon. To use nodemon, install it globally on your machine using npm i -g nodemon (you'll probably need admin rights to do this). Then, run your application using nodemon instead of node.
nodemon <path/to/main>.js

Node.js: accessing mysql database

I am writing a Node.js application. In my node-modules/abc/static/example.js file, I want to access the mysql records by querying to the database. Is it possible to do so?
When I include mysql like this:
var mysql = require('mysql');
I get an error:
Uncaught ReferenceError: require is not defined
Is it because it is on client side? What are the other options to access mysql database from the 'example.js' file?
I'm going to guess that you're attempting to use server side js in the client side.
You need to npm install a mysql adapter, #coreyg suggested this one (https://www.npmjs.com/package/mysql).
Set up a nodejs project (if you have not already done so):
npm init
npm install --save mysql
You would then typically create some sort of webapp that would serve up a url in the client side. You'd then (using ajax) request the url.
Behind the scenes your webapp then would query the mysql database (using the adaptor you installed) with whatever query you had in mind.
Once your ajax call had finished you'd run your callback which would do what you wanted with the data that had been returned from the database.
Thats the basic theory. If you want further information on how to do this I'd suggest reading this question: How do I get started with Node.js
Following on Neil Munro's Answer,
after initiating nodejs and installing mysql npm package,
you can actually execute your code from the terminal. to do that,
you can create a new js file on the same folder you are executing those commands,
say mysqlTestProject.js
inside this file, you can put what you had previously, (require stuff and all). for example:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
`` codes were taken from https://www.npmjs.com/package/mysql
and then from the terminal (still on the same folder as you were),
type in this line
node ./mysqlTestProject.js

How to localhost a webapp with nodejs

I'm working through designing my first webapp, I've already written a significant portion of the frontend and now I want to make a very simple backend to begin implementing some of the functionality. I've spent the last few days learning as much as I can about effective backend development and other various things, but I've run into a huge problem. I fundamentally don't understand how to attach my front end and my backend (which I want to use nodejs for).
All I want is to use my browser to go to localhost:8080 and automatically see the html document with my frontend then within my frontend code have the app communicate with the server (to get json info or instruct the server to add things to a database or things like that).
Once you have installed node in your system.
Folder structure:
Keep your files in public folder inside app folder
Navigate to your application folder in Terminal or Command Prompt:
Then create a file as package.json and keep following code in it:
{
"name" : "YourAppName",
"version" : "0.0.1",
"description" : "App description",
"dependencies" : {
"mime" : "~1.2.7"
}
}
then come back to terminal and run npm install
Then create a file as server.js and keep following code in it:
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};
function send404(responce){
responce.writeHead(404,{"content-type":"text/plain"});
responce.write("Error 404: resourse not found");
responce.end()
}
function sendFile(responce,filePath,fileContents){
responce.writeHead(200,{"content-type": mime.lookup(path.basename(filePath))});
responce.end(fileContents);
}
function serveStatic(responce,cache,abspath){
if(cache[abspath]){
sendFile(responce,abspath,cache[abspath]);
}else{
fs.exists(abspath,function(exists){
if(exists){
fs.readFile(abspath,function(err,data){
if(err){
send404(responce);
}else{
cache[abspath] = data;
sendFile(responce,abspath,data);
}
})
}else{
send404(responce)
}
})
}
}
var server = http.createServer(function(request,responce){
var filePath = false;
if(request.url == '/'){
filePath = 'public/index.html';
}else{
filePath = 'public'+request.url;
}
var abspath = './'+filePath;
serveStatic(responce,cache,abspath);
})
server.listen(8080,function(){
console.log("server running on 3000");
})
** This code is to help you get started with node js, for better understanding go to node documentation. Read about the mime module too, it is being used here.
You can use free cloud services such as Parse.com. this js sdk
You can use Grunt and using Connect plugin, create a simple server, sufficient for developing pure JS web applications.
Using Grunt basically requires 2 files
package.json
Gruntfile.js
package.json defines the dependencies required by Grunt to run. In your case it would include
grunt
grunt-contrib-connect (The plugin for setting up a server)`
It may also include additional dependencies based on your requirements.
Gruntfile.js defines the configuration for dependencies. In your case how the server should be setup. If you use plugins other that grunt-contrib-connect you should configure them too.
Reference:
Grunt: The JavaScript Task Runner

heroku node.js tutorial - send env variables to other js pages

so i'm in the process of doing the 'getting started' on the heroku page.
by cloning their tutorial repo, i have decided to add my own index.html and app.js files into the /public folder they already created for me.
directory looks like this:
node-getting-started repo folder
| node_modules folder
| public folder
| | app.js
| | index.html
| index.js
| package.json
| Procfile
the package.json's main points to index.js which looks like this:
index.js
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
var obj = { ... };
var secret_key = process.env.SECRET_KEY;
// what should i do here to send the variables above to my app.js file?
// response.send(secret_key) ???
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
at this point, what i'm trying to do is send that obj within the index.js to my app.js file so i can use it there.
is this is the right way to go about this? is there some other (proper?) way of sending it to the other file?
i would basically want to do the same thing with environment variables such as setting a var secret_key = process.env.SECRET_KEY in the index.js and sending it to the app.js so that i could use it there, too.
Could someone explain to me how I could go about doing this?
In order to pass varying data from the server to the page being viewed you need to render it. This is different from serving a static file.
Express supports different template engines such as Jade, EJS and Handlebars. Here's a quick example using little help from express-generator. First create example project by running
$ mkdir example
$ cd example
$ sudo npm install -g express-generator
$ express -e
Then in routes/index.js you can find the relevant part that renders view called index and passes a title along.
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
The next part of your problem is to figure out howto pass data from your html to the app.js loaded in <script> element.
Assuming you would like to keep the SECRET_KEY hidden from users, you can't send it to the client. In that case, you'll want to move the functionality that requires the key to the server.
For an API request that requires a key, have the client request to your server and the server will make the request to the API with the key. You'll want to modify the app.get route:
// '/api-request' will be the URI that the client uses
// the callback will handle what the server does when it receives a request with this URI
app.get('/api-request', function(req, res){
request('API_URL' + process.env.SECRET_KEY, function(err, data) {
// send error to the client -- res.send exits the function and ends the request
if (err) res.send(err)
// send data to the client
res.send(data)
})
})
Your server will act as a middleman to the API, keeping your key unexposed and contained to the server.
On the client, the request will receive whatever data the server sends back with res.send. Client has no idea there was a middleman involved.
// the browser is smart and knows that a leading / refers to the current domain
request('/api-request', function(err, data) {
if (err) // handle error
// do stuff with the data
console.log(data)
})
Other operations that require a key can be handled in a similar manner. Your server will need a route to which the client will send a request with any relevant info and the server will send any resulting data.

Categories