How to serve client-js from push-it using node.js - node.js

I have just started using node.js. My mayor problem is lack of documentation but I'm getting through and I really like it
Now I'm trying to use push-it which sits on top of socket.io. The Docs mention to serve the static client-js file, but I don't know how to do that. I already tried different paths. Socket.io works out of the box, but I can't find how to do it for push-it.
I installed push-it using npm
Thanks for any tips,
Miguel

you can use connect or express to server static files,
exactly as the dnode docs suggest.
__dirname is the directory you're running from, it's common to use __dirname + '/public' and place your files in there
var connect = require('connect');
var server = connect.createServer();
server.use(connect.staticProvider(__dirname));
var dnode = require('dnode');
dnode(function (client) {
this.cat = function (cb) {
cb('meow');
};
}).listen(server);

Related

Best Practice to create REST APIs using node.js

I am from .Net and C# background and I am new to Node.js. I am working on a project, which is mix of MongoDB and Node.JS.
In MongoDB, data from various tools is stored in different different collections. I have to create multiple REST APIs using Node.JS for CRUD operation on that data, these APIs will be called from React.JS application.
I want to keep APIs into separate files for seperate tool and then calling including all files into app.js file.
Please help me with best approach.
For POC purpose, I created a node.js application, where I created app.js file and written all my code for GET|POST|DELETE APIs. This is working fine.
var _expressPackage = require("express");
var _bodyParserPackage = require("body-parser");
var _sqlPackage = require("mssql");
var app = _expressPackage();
var cors = require("cors");
var auth = require('basic-auth');
var fs = require('fs');
const nodeMailer = require('nodemailer');
//Lets set up our local server now.
var server = app.listen(process.env.PORT || 4000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.get("/StudentList", function(_req ,_res){
console.log("Inside StudentList");
var Sqlquery = "select * from tbl_Host where HostId='1'";
GetQueryToExecuteInDatabase(_req,_res, Sqlquery,function(err,data){
console.log(data);
});
});
Don't know exactly what your app intends to do, but usually if you are not serving webpages and your API is not too complex, there is no need to use express. You can build a simple server natively in NodeJS to serve data.
Additionally, if your app has many routes (or is likely to in the future), it is a good idea to put helper functions like GetQueryToExecuteInDatabase() in a separate file outside of app.js such as utils.js.
Based on what I have understood about what you want to do, your file structure should look something like this:
data (db related files)
services (contains one file per api service)
app.js
utils.js
Hope this helps.

How to make Socket IO work over HTTPS using node.js

This is frustrating me like crazy!
i'm using a proxy so that any requests that go to myurl/APP/ are answered by node.js at myurl:8001
I now need this to work over https. easy.... i thought.
i have Apache serving up the old version from the public folder. That is stand alone, and when i'm done building this, it will just be removed. but for now needs to remain in tact and accessible. Lets encrypt is setup on this. and https://myurl works fine, showing content from the public folder of course.
if i go to https://myurl:8001 then chrome says "site can't be reached". If i go to http://myurl:8001 it works fine. I think this is because https default port is 443. I have VPS not dedicated so i don't think i can alter that. And surely if i did alter the ssl port then it wont work for the public folder??
i'll show you the basics of whats going on;
app.js;
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(8001);
console.log("Server started.");
var SOCKET_LIST = {};
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket.number = "" + Math.floor(10 * Math.random());
SOCKET_LIST[socket.id] = socket;
socket.on('disconnect',function(){
delete SOCKET_LIST[socket.id];
});
});
setInterval(function(){
var pack = [];
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.x++;
socket.y++;
pack.push({
x:socket.x,
y:socket.y,
number:socket.number
});
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('newPositions',pack);
}
},1000/25);
client/index.html;
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var socket = io.connect('http://www.myurl:8001', {path: "/socket.io"});
socket.on('newPositions',function(data){
ctx.clearRect(0,0,500,500);
for(var i = 0 ; i < data.length; i++)
ctx.fillText(data[i].number,data[i].x,data[i].y);
});
</script>
It works fine as the code is but only over http. I need this to work over SSL
i need this line to work when its https;
var socket = io.connect('https://www.myurl:8001', {path: "/socket.io"});
How is this possible?
any help is greatly appreciated.
Your server code is only creating an http server, not an https server and since socket.io uses your http server, it will only run on http. http and https servers are different (the https server implements certificate verification and data encryption which is not present with the http server).
To make an https server, change this:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
to this:
const express = require('express');
const app = express();
const options = {...}; // fill in relevant certificate info here
const serv = require('https').createServer(options, app);
And, you will have to fill in the appropriate certificateinfo in the options data structure.
https.createServer() code examples are here.
You can then run your https server on any port you want as long as you connect to it with an https URL and the right port number. You are correct that the default port for an https URL is 443 so if not port number is specified, that's what a browser will attempt to use.
Ok this was a bit embarrasing... the actual problem i had was because of the following.
If you can follow this lol...
So in dreamhost they allow you to run apache and serve content in the usual way. there is a /public folder for this. fairly standard stuff.
Because i'm trying to branch out into being able to use sockets (please don't lecture me on using sockets with PHP... let it go!) So i was using dreamhost which allows a person to proxy a node.js app through a port. eg. port xxxx ends up at thewebsiteurl/whateverfolderyouchoose/
ok so in my node.js i was using express. now in express you can specify routing really easy. For some bizzare reason, i cant be bothered to actually find out why, if you know please enlighten me... i had to put double forward slash in the routing, like so "//whateverroute/". all the examples i was learning from use a single forward slash. eg "/whateverroute/" but that didn't work. if you know why, please tell us. So before i figured this out, i couldn't actually route anything correctly, hence having to use the url with the port number at the end. of course that messes up the https. example, https://www.theurl.com:xxxx wasnt secure, because the node.js app wasnt running an https res req server. Actually i did set up the https node server and thought that was the solution to the problem at first.
So the solution to this bizarre problem was the node.js routing. ofcourse its stupidly complicated because, hey life's like that when your learning from google and not someone who actually knows your exact setup.
What turns out to be funny is, i cant stand node.js. I can see the benefit to using it. But it seems like alot of ball ache for something as simple as what i'm making. Also i have now discovered phone/gap so php actually is ok for what i want to do. Ok so i'm hitting the server way to many times with AJAX requests but it's coping with a few hundred users right now and when it hits the 10'000 mark when the site probably wont work very well, i should be making enough to get a real node.js programmer in to learn from.... hopefully.
I do appreciate the help tho guys.

How to use a package for node in angular 2

I am doing a school project to teach us the basics of a bittorrent client. I decided to use node-torrent found here https://www.npmjs.com/package/node-torrent to help me. It is made for node, I am using angular 2.
I want to know if it is possible to implement this in an angular 2 web application and if not, how I would otherwise use it. I am pretty new to angular. I have attempted to just follow the tutorial which has us using this bit of code:
var Client = require('node-torrent');
var client = new Client({logLevel: 'DEBUG'});
var torrent = client.addTorrent('a.torrent');
// when the torrent completes, move it's files to another area
torrent.on('complete', function() {
console.log('complete!');
torrent.files.forEach(function(file) {
var newPath = '/new/path/' + file.path;
fs.rename(file.path, newPath);
// while still seeding need to make sure file.path points to the right place
file.path = newPath;
});
});
But the problem is I have no idea where to implement this. Also, usually there is a way to add this to my package.json in angular 2 with a npm install, but there is no indication of how to do that. I am assuming I have to download it?

Heroku Postgres Connecting in Node.js

I want to use a heroku database (already deployed in heroku) for my AngularJS application created using Yeoman. I want to persist my data that is currently an array of JSON objects that goes away when I refresh the page. I am trying to follow Heroku's guide for Node.js here (https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js) but it is very shot, no examples, and I am fairly new to servers/databases. I have a 'web.js' file and the Procfile int my root directories for Node.js and heroku to read that file. I have the "dependencies" already set but I am not sure what is happening in this code below that heroku provides
var pg = require('pg');
pg.connect(process.env.DATABASE_URL, function(err, client) {
var query = client.query('SELECT * FROM your_table');
query.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
First: Where do I put this code?
Second: What is happening here?
and Third: How do I use it to upload my data that is currently an array of JSON objects that I
hardcode into my code into the heroku database?
My web.js file
var gzippo = require('gzippo');
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(gzippo.staticGzip("" + MyApp + "/dist"));
app.listen(process.env.PORT || 9000);
My Procfile
web: node web.js
That code goes in your web.js file.
I'm pretty sure it's accessing your database and setting the results to the variable query so you can access the data.
I think want you want for pushing the data is to look here, particularly at pg:push.

Any Easy to extend Web-based File Manager for node.js?

Want to find one and modify that to read, write file on mongoDB gridfs store
You could try Cloud Commander node.js-based orthodox file manager. It could be used as middleware for express this way:
var http = require('http'),
cloudcmd = require('cloudcmd'),
express = require('express'),
io = require('socket.io'),
app = express(),
PORT = 1337,
server,
socket;
server = http.createServer(app);
socket = io.listen(server);
app.use(cloudcmd({
socket: socket, /* used by Config, Edit (optional) and Console (required) */
config: { /* config data (optional) */
prefix: '/cloudcmd', /* base URL or function which returns base URL (optional) */
}
}));
server.listen(PORT);
When you need a file tree you could try this angular/node based example.
Nodepad:
This tutorial will give you a good idea on how it was made: http://dailyjs.com/2010/11/01/node-tutorial/ As knowing how it was made it should make it heaps easer to extend it. :) It is quite basic, I'm re-writing the whole thing myself :P
Nodepad on github: https://github.com/alexyoung/nodepad
It even uses MongoDB, I'm going to do the opposite to what you wanted to do and that is make it not use MongoDB. :P
Take a look at https://github.com/OpusCapita/filemanager
It has a NodeJS server implementation and react client implementation.
Can be easily extended using "connectors"

Resources