Node.js socket.io - node.js

My IP address is 192.168.1.6
OS : Windows 7
Working directory : c:\ArduinoJs
My node.js file is located in C:\ArduinoJS folder named as serialtoJSON.js listen (8080)
My index.html file is located at
c:\ArduinoJS , the same place where node.js file is located.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://192.168.1.6:8080/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src='https://swww.tokbox.com/v1.1/js/TB.min.js'></script>
<script type="text/javascript" src="http://static.pureexample.com/js/flot/jquery.flot.min.js"></script>
$(function() {
// open a connection to the serial server:
var socket = io.connect('http://192.168.1.6:8080');
This is working fine.
But I want to keep the .js files in C:\ArduinoJS\js and load from them.
Hence I changed the above script to
<script src="js/jquery-1.8.3.js"></script>
But this is giving 404 error.
How can I load .js files like jquery-1.8.3.js ,TB.min.js etc from my own computer.

Use express to serve files from a directory.
For the following example: create a new sub-directory where you got (your starting point) serialtoJSON.js named client
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
app.use(express.static(__dirname + '/client')); //Store the index and js here
http.listen(8080, function(){ console.log('[+] Server listening # :8080');});

Related

Can i connect an already created angular project with nodejs(express)

I already created an angular website in which i have done routing and connected to firestore. but now i want a middleware connection because i want the values scanned by RFID scanner(Rasberry PI)to get stored in firestore.
So can i connect this angular project with node as per now or do i need to rebuild my app?
I already tried to connect using node js but when i am running the server the screen is blank and only title is displayed
------IN SERVER.js---------
const express = require('express');
const path = require('path');
const http = require('http');
// const bodyParser = require('body-parser');
// const morgan = require('morgan');
const proxy = require('express-http-proxy');
// const cors = require('cors');
const request = require('request');
const app = express();
// app.use(cors());
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on ${port}`));
-------IN DIST/index.html --------
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Miracle Bus Track</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
The answer is 'yes', as client side JS UIs are usually decoupled from backend and can be hosted wherever.
However, your specific issue sounds like a code/build issue that Stackoverflow won't be a good place to sort out. One thing I see is you don't reference a tag anywhere for the angular javascript so you should start there.
Looking at the scenario you mentioned, I would like to suggest you some different approach to handle this.
I would suggest you to use Google Cloud function https://cloud.google.com/functions/ instead of creating your own nodejs server.
Cloud functions are serverless functions run on nodejs server.
I am suggest this because you are already using Firestore.
I am suggesting so e architectural changes in your project.
Google also provide IOT module. That may help you more to cuumunicate to your Raspberry Pi.

Get URL value in static page in Express.js

I am beginner to node and express. In my current application the page is displaying using this code :
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
and in static folder, there are there files:
css, index and a js file
Listening to 3000 port it is working normally.
But what if I want to access URL like this :
localhost:3000/name=someName
I want to use this name parameter in my js file which is available in static folder.
or suggest any other routing method to do that?
If you want to get the query parameters in your .js file it can be done. So the code would look like this:
Server (index.js)
"use strict";
var express = require("express");
var serveStatic = require('serve-static');
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
app.listen(3000);
console.log("Static express server started");
HTML (/static/index.html)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body onLoad="readParameters()">
<div>
<h3 id="1" >Loading..</h3>
</div>
</body>
</html>
Client side JavaScript (/static/test.js)
var readParameters = function()
{
console.log('Getting parameters..');
let params = (new URL(location)).searchParams;
console.log('Query parameters: ', params.toString());
var html = 'Query parameters: ';
for (let p of params) {
html += "<br/>" + p.toString();
}
$("#1").html(html);
}
Then you can test by entering:
http://localhost:3000/?test=value
Into your browser.
You should see:
Query parameters: test=value
on the index page.
The code tree should look like this:
root
¦ index.js
¦
+---static
index.html
test.js
3 Files:
/index.js (Node server side code)
/static/index.html (HTML)
/static/test.js (Test JavaScript file)
You can defined route like below,
router.get('/name=:id', function(req, res, next) {res.render('index', { title: req.params.id});});
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. This captured values we can access with 'req.params' object. for reference https://expressjs.com/en/guide/routing.html

Cannot load stylesheets node

I have created basic node/express server
var express = require('express');
var app = express();
var path = require('path')
var port = 8080;
app.use("/styles", express.static('../public/styles'));
app.get('/' , function( req , res ){
console.log(__dirname)
res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)
structure of project is simple
app
public
html
index.html
styles
javascripts
routes
server.js
html file looks very simple
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../styles/index.css">
<title> Hello world!</title>
</head>
<body>
</body>
</html>
yet it still complains
GET http://localhost:8080/index.css 404 (Not Found)
Yet my paths should be correct , i looked up this problem and every answer is about using
app.use("/styles", express.static('../public/styles'));
so browser know how to redirect when looking for a stylesheets. Which does not work for me.
Could anybody help with this common problem?
Thanks!
Not clear what your project structure is. It's more common to have app.js in your project directory contain the basic express server and if you have complicated routing, do that in routes/server.js
So you could change your project structure:
app.js (main file)
public
index.html
styles
index.css
javascripts
routes
server.js --not needed?
If that's the case, change app.js to:
var express = require('express');
var app = express();
var port = 8080;
//use static folder public to serve everything up
app.use(express.static('./public/'));
app.listen(port)
In index.html, to include index.css:
<link rel="stylesheet" href="/styles/index.css" >

How to share common function between server and client using node.js

Following are the structure of my application
Inside prototype.js file i have following code:
(function(exports) {
exports.foo = function() {
return 'bar';
};
})((typeof process === 'undefined' || !process.versions) ? window.common = window.common || {} : exports);
app.js contains
var express = require('express'),app = express(),server = require('http').createServer(app),io = require('socket.io').listen(server),port = 3000,path = require('path');
var common = require('common/prototype');
console.log(common.foo());
// listening to port...
server.listen(port);
//Object to save clients data
var users = [];
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.sendfile('/public/index.html');
});
index.html contains
<!doctype html>
<html lang="en">
<head>
<title>Socket.io Demo</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="/common/prototype.js"></script>
<script>
alert(window.common.foo()); //This line will gives me an error TypeError: window.common is undefined
</script>
</body>
</html>
Now i would like to print
Hello, I am bar from server and client as well.
Now i am able to print from server side using following line
var common = require('common/prototype');
console.log(common.foo());
But could not able to show alert on client side. could you please help me to find the root cause for the issue.
The root cause is that when you do <script src="/common/prototype.js"></script> in your HTML the file won't be fetched because the Express static middleware is only looking for files under your public folder.
A quick way to test this is to copy your prototype.js to your javascript folder inside public. Then update your script tag to reference the file as follows <script src="/javascripts/prototype.js"></script>
The thing to remember is that the JavaScript files that live under node_modules are not automatically available to the browser.

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Resources