Any Easy to extend Web-based File Manager for node.js? - 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"

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 embed multiple instances of node-red in node app

Node-red documentation here gives info on how to embed a single node-red app inside a nodejs app - http://nodered.org/docs/embedding
We wanted our site's users to have their own node-red's on different ports for some custom programming. Is it possible to embed multiple node-red apps in a nodejs applicaiton?
I tried repeating same steps for embedding by changing settings of each call with different port but only one time it is created. First time, a node-red instance is created based on settings. Next time we call, we get port in use. I assume this has something to do with node require doing caching and all... Any workaround for this issue?
If you're interested I created a fork of the node-red project allowing this feature.
this is how you would initiate it:
var http = require('http');
var express = require("express");
var RED = require("node-red")();
var RED2 = require("node-red")();
// Create an Express app
var app = express();
// Add a simple route for static content served from 'public'
app.use("/",express.static("public"));
// Create a server
var server = http.createServer(app);
// Create the settings object - see default settings.js file for other options
var settings = {
httpAdminRoot:"/red1",
httpNodeRoot: "/api",
userDir:"./hhh",
functionGlobalContext: { } // enables global context
};
// Initialise the runtime with a server and settings
RED.init(server,settings);
console.log(RED2.settings === RED.settings, 888, RED2.settings.userSettings);
// Serve the editor UI from /red
app.use(settings.httpAdminRoot,RED.httpAdmin);
// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot,RED.httpNode);
server.listen(8005);
// Start the runtime
RED.start();
var app2 = express();
app2.use("/",express.static("public"));
var server2 = http.createServer(app2);
var settings2 = {
httpAdminRoot:"/red2",
httpNodeRoot: "/api",
userDir:"./hhhh",
functionGlobalContext: { }
};
RED2.init(server2,settings2);
app2.use(settings2.httpAdminRoot,RED2.httpAdmin);
app2.use(settings2.httpNodeRoot,RED2.httpNode);
RED2.start();
server2.listen(8006);
console.log(RED.settings.httpAdminRoot);
console.log(RED2.settings.httpAdminRoot);
console.log(RED2.settings === RED.settings);
also, works on the same port. but make sure to use different paths is so.
https://github.com/aryeharmon/node-red
No, currently Node-RED has no multi-user capabilities and no way to instantiate multiple instances in one process.
You'll have to run separate instances of the application for each user. Have a look at something like FRED for an example of this. This runs individual instances and proxies them to make the integration look like it's all on the same port/domain

Node.JS express server creation methods difference

I have recently inherited a project of a Node.JS and Express based API, and I have noticed express server creation is as such (simplified version):
// http is required.
var http = require('http');
var express = require('express');
var app = express();
// Note http is used to create server, and app is used as param:
http.createServer(app).listen(3000, function (request, response) {
console.log('listening on port 3000');
});
Everything works as expected of course.
I have been trying to figure out what exactly is happening behind the scenes here, mostly in comparison to the method in Express API, which shows:
// http is not required.
var express = require('express');
var app = express();
// Note Express is used to create the server:
var server = app.listen(3000, function () {
console.log('listening on port 3000');
})
Note the difference in server creation using http, and using Express directly.
Is there any benefit in using a specific one of the two method? What is the actual difference between the two?
Micro-optimization-wise, is it preferred to avoid requiring 'http', which is probably required by express anyway?
Thanks from ahead!
Both are more or less functionally equivalent, in the second example the express constructor returns a new object which effectively wraps up the http.createServer call internally (i.e. when you call app.listen).
If you are going to use express then you should use it's recommended APIs, the first approach is considered outdated.

Can I define Express routes in a child process?

So I run a bunch of a little chatbots written in node, nothing too exciting. However, I recently decided to give them their own little web page to display information in a graphical manner. To do this, I figured I'd just run express.
However, I'm running my bots with a wrapper file that starts each chatbot as a child process. Which makes using express a little tricky. Currently I'm starting the express server in the wrapper.js file like so:
var express = require("express");
var web = express();
web.listen(3001);
And then in the child processes, I'm doing this:
var express = require("express");
var web = express();
web.get("/urlforbot",function (req,res) {
res.send("Working!");
});
However, when I navigate to :3001/urlforbot, I get Cannot GET /urlforbot.
Any idea what I'm doing wrong and how to fix this?
Edit: This is my complete wrapper file: http://snippi.com/s/3vn56m2
Edit 2: This is what I'm doing now. I'm hosting each bot on it's own port, and storing that information in the configs. This is the code I'm using, and it appears to be working:
web.get("/"+cfg.route, function (req,res) { // forward the data
res.redirect('http://url.com:'+cfg.port+"/"+cfg.route);
});
Since your bots run as separate processes (any particular reason?), you have to treat each one as having to implement their own HTTP server with Express:
var express = require("express");
var web = express();
web.get("/urlforbot",function (req,res) {
res.send("Working!");
});
web.listen(UNIQUE_PORT_NUMBER);
Each bot process needs to listen on a unique port number, it can't be shared.
Next, you need to map requests coming in on port 3001 in the 'master' process to the correct child process' Express server.
node-http-proxy has a useful option called a ProxyTable with which to create such a mapping, but it requires the master process to know what the endpoint (/urlforbot in your terms) for each bot is. It also requires that the master knows on which port the bots are listening.
EDIT: alternatively, you can use child_process.fork to fork a new process for each of your bots, and communicate between them and the master process (port numbers and such, or even all the data required to generate the /urlforbot pages) using the comm channel that Node provides, but that still sounds like an overly complex setup.
Wouldn't it be possible to create a Bot class instead? You'd instantiate the class for each bot you want to run, and that instance loads its specific configuration and adds its routes to the Express server. All from the same process.

Resources