Pass a parameter to another JavaScript and run the script - javascript

Send a parameter(URL) from another script through recursion to this script.
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var murl = 'mongodb://localhost:27017/getData';
url = '';
app.get('/getData', function(req, res){
firstCall(req,res)
//console.log("cookie",req.cookies);
})
var firstCall = function(req, res, data){
console.log("URL: ", url);
res.send('Check your console!');
}
app.listen('3000')
console.log('Magic happens on port 3000');
module.exports = function(app) {
app.get('/getData', function() {});
};
I want this code to act as backbone or logic board. And some other file should be able to trigger this logic board file by adding the URL to this file.
Like we pass parameters to function to call. How do I do it here.

Related

get request with vanilla javascript and express js

I am trying to practice making a get request with vanilla javascript to express server, but I am stuck in receiving the request in express js (my terminal does not print anything in my get request call).
Am I missing something that my express did not listen to my get request at all?
front end:
(function () {
var retrieve = document.getElementById('retrieve'),
results = document.getElementById('results');
retrieve.addEventListener('click', function (e) {
var oReq = new XMLHttpRequest();
console.log('GET', e.target.dataset.url);
oReq.open('GET', e.target.dataset.url, true);
oReq.onload = function () {
console.log('Inside the onload event');
if(oReq.readyState === 4){
if(oReq.status === 200){
console.log(oReq.reponseText, "pass");
}
else{
console.error(oReq.statusText);
}
}
};
oReq.onerror = function(e){
console.error(oReq.statusText, "error");
}
oReq.send(null);
});
}());
<h1>Vanilla Ajax without jQuery</h1>
<button id="retrieve" data-url="/">Retrieve</button>
<p id="results"></p>
express code:
var express = require('express');
var path = require("path");
var bodyParser = require('body-parser');
var morgan = require('morgan');
var db = require('./db');
var cors = require("cors");
var app = express();
app.use(cors());
app.use(bodyParser.json());
app.use('/', express.static(path.join(__dirname, '../client')));
app.get("/", function(req,res){
console.log("get");
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})

How to extract zip from client in node

I'm having a node app which needs to get some zip file from client Postman and extract it to a folder in my fileSystem,Im using express I did the following which doesnt work,
what am I missing here?
I've created sample node app to simulate the issue.
var express = require('express');
var upload = require('multer')({ dest: 'uploads/' });
var admZip = require('adm-zip');
var app = express();
app.post('/',upload.single('file'),function(req,res){
debugger;
var zip = new admZip(req.file);
zip.extractAllTo("C://TestFolder//TestPathtoExtract", true);
res.send("unzip");
});
var server = app.listen(3001,function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
})
This is how I use it im postman
If there is other way to do it with different open source this can be great!
I use
https://github.com/cthackers/adm-zip
which can be change to any other library
I've also find this lib but not sure how to use it with express
https://www.npmjs.com/package/decompress-zip
Thanks!
This is the set up I did for Postman, first this is my form-data body
Now in the header I left in blank after trying to set multipart/form-data manually and utterly failed, so no header here.
Here I did a pair of console.log, one of req.headers to be sure of Postman sending the right multipart/form-data and another of req.file
And well the output seems to be fine
Edit: the code.
var express = require('express');
var upload = require('multer')({
dest: 'uploads/'
});
var admZip = require('adm-zip');
var app = express();
app.post('/', upload.single('file'), function(req, res) {
console.log('%c > req.headers test.js [9] <=================================', 'color:blue;', req.headers);
debugger;
console.log('%c > req.file test.js [10] <=================================', 'color:blue;', req.file);
//instead of just req.file I use req.file.path as admzip needs the actual file path
var zip = new admZip(req.file.path);
zip.extractAllTo("/Users/myuser/Desktop/ext", true);
res.send("unzip");
});
var server = app.listen(3001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You need to pass filename as argument.
Use req.file.path
var zip = new admZip(req.file.path);

socketstream tutorials/authentication can't use Everyauth with the chat demo

https://socketstream.github.io/socketstream/docs/#/tutorials/authentication
when i put the codes in this section to the demo project(real time chat), the chat function doesn't work. can any one help me with this?
here's my code:
// ===================== SEPARATOR ============
var ss = require('socketstream');
var redirect = require('connect-redirection');
var everyauth = require('everyauth');
var http = require('http');
var conf = require('./conf/conf');
var auth_twitter = conf.oauth.twitter;
// Define a single-page client called 'main'
ss.client.define('main', {
view: 'app.html',
css: ['../node_modules/normalize.css/normalize.css', 'app.css'],
code: ['../node_modules/es6-shim/es6-shim.js', 'libs/jquery.min.js', 'app'],
tmpl: 'chat'
});
ss.http.middleware.prepend(redirect());
// Serve this client on the root URL
ss.http.route('/', function(req, res){
// if(!req.session.userId){ return res.redirect('/login'); }
res.serveClient('main');
});
// Use server-side compiled Hogan (Mustache) templates. Others engines available
ss.client.templateEngine.use(require('ss-hogan'));
// Minimize and pack assets if you type: SS_ENV=production node app.js
if (ss.env === 'production') ss.client.packAssets();
everyauth.twitter
.consumerKey(auth_twitter.KEY)
.consumerSecret(auth_twitter.SEC)
.findOrCreateUser( function (session, accessToken, accessTokenSecret, twitterUserMetadata) {
var userName = twitterUserMetadata.screen_name;
console.log('Twitter Username is', userName);
session.userId = userName;
session.save();
return true;
})
.redirectPath('/');
var bodyParser = require('body-parser');
//ss.http.middleware.prepend(bodyParser.urlencoded());
//ss.http.middleware.append(everyauth.middleware());
var server = http.Server(ss.http.middleware);
server.listen(3000);
ss.start(server);
After reading some doc, i tried this and it worked:
replace the last three lines codes:
var server = http.Server(ss.http.middleware);
server.listen(3000);
ss.start(server);
with this:
ss.start();

combining functionality of two Node servers with different initial set up

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?
You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

Creating a javascript object and binding this

I'm trying to build my first node app. My app.js file is shown below. I want to access this from aother module by doing 'app = require('app')'. I then want to access app.app, app.dbConn and app.models
The problem is that when I require this module, app.models is not present on the resulting object.
var express = require('express');
var path = require('path');
var orm = require('orm');
var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');
module.exports = new function(){
this.app = express();
// middlewares must be added in order - start with the basics
environment(this.app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }
// add models to the request early in the middleware chain
this.dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
this.models = db.init(this.dbConn);
this.app.use(function(req,res,next){
req.models = this.models;
next();
});
passport = auth.init(this.models);
authRouter = auth.router(passport)
this.app.use('/users', authRouter);
this.app.use(mainRouter);
}
}.bind(this));
this.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
}
The only way to implement what I wanted was with a function that takes a callback, in the end I rewrote my code thus:
var express = require('express');
var path = require('path');
var orm = require('orm');
var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');
var app;
module.exports = function(cb){
app = express();
// middlewares must be added in order - start with the basics
environment(app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }
// add models to the request early in the middleware chain
dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
models = db.init(dbConn);
app.use(function(req,res,next){
req.models = models;
next();
});
passport = auth.init(this.models);
authRouter = auth.router(passport)
app.use('/users', authRouter);
app.use(mainRouter);
cb({
dbConn: dbConn,
app: app,
models: models
});
}
});
}
if (!process.env.TESTING) {
module.exports(function(server){
server.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
});
}
app.models is defined only once database connection is completed: you cannot use it right away after requiring the module. You should provide an entry point that accepts a function to call once the connection is ready and call this function inside the orm.connect callback.
Even the "server started" message is a bit misleading as it's shown before the server can actually do anything because the function passed to orm.connect has not been called yet.
app.models is never defined so it is never available.
Instead, try
app.set('models', db.init(this.dbConn);

Categories

Resources