Getting Error "Error: Cannot enqueue Handshake" Using node-mysql For MS SQL Server and node App Connectivity? - sql-server

I have developed a REST api using node.js. My api is running on my macbook. I am trying to access MS SQL server running on another machine using node-mysql module, but while trying to create a connection I am getting the following error:
GET /contacts/ 200 12.467 ms - -
events.js:141
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
at Protocol._validateEnqueue (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Protocol.handshake (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/mysql/lib/Connection.js:123:18)
at read_json_file (/Users/abc/Desktop/NodeProjects/MyWebsite/models/contacts.js:15:14)
at Object.exports.list (/Users/abc/Desktop/NodeProjects/MyWebsite/models/contacts.js:29:22)
at /Users/abc/Desktop/NodeProjects/MyWebsite/app.js:38:44
at Layer.handle [as handle_request] (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/abc/Desktop/NodeProjects/MyWebsite/node_modules/express/lib/router/route.js:112:3).
I have no Clue what this is saying, Can some one guide me through this?
The code of my two scripts is given below for understanding the problem?
I am trying to connect to the MS Sql server through contacts.js scripts's "function read_json_file()" function.
App.js script code:
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var url = require('url');
var routes = require('./routes/index');
var contacts = require('./models/contacts');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//app.use('/contacts', contacts);
// catch 404 and forward to error handler
app.get('/contacts',function(request, response){
var get_params = url.parse(request.url, true).query;
if (Object.keys(get_params).length == 0)
{
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.list()));
}
else
{
response.setHeader('content-type', 'application/json');
stringify(contacts.query_by_arg(get_params.arg, get_params.value));
}
});
app.get('/contacts/:number', function(request, response) {
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.query(request.params.number)));
});
app.get('/groups', function(request, response) {
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(contacts.list_groups()));
});
app.get('/groups/:name', function(request, response) {
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(
contacts.get_members(request.params.name)));
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
module.exports = app;
contacts.js script code:
var fs = require('fs');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.***.***', //Ip address of the server machine
port : '****', //Port number
user : 'ab',
password : 'abc',
database : 'MyDataBase'
});
//Read Json file
function read_json_file() {
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();
var file = './data/contacts.json';
return fs.readFileSync(file);
}
//Parse the the file da
exports.list = function() {
return JSON.parse(read_json_file());
};
exports.query = function(number) {
console.log('contact Number is:: '+number);
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
for (var i = 0; i < result.length; i++) {
var contact = result[i];
if (contact.primarycontactnumber === number) {
return contact;
}
}
return null;
};
exports.query_by_arg = function(arg, value) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
for (var i = 0; i < result.length; i++) {
var contact = result[i];
if (contact[arg] === value) {
return contact;
}
}
return null;
};
exports.list_groups = function() {
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
var resultArray = [];
for (var i = 0; i < result.length; i++) {
var groups = result[i].groups;
for (var index = 0; index < groups.length; index++) {
if (resultArray.indexOf(groups[index]) === -1) {
resultArray.push(groups[index]);
}
}
}
return resultArray;
};
exports.get_members = function(group_name) {
var json_result = JSON.parse(read_json_file());
var result = json_result.result || [];
var resultArray = [];
for (var i = 0; i < result.length; i++) {
if (result[i].groups.indexOf(group_name) > -1) {
resultArray.push(result[i]);
}
}
return resultArray;
};

Use mussel module https://github.com/patriksimek/node-mssql . Follow the samples.

Related

Facebook messenger that sends a message manually if the user subscribed

I'm making a bot that let my students get a school meal menu. I'd like it to send a list of menu to students 10 minutes before the lunch time.
How should I make a code for this in JavaScript?
The main problem I encountered with was how to check the time so that my bot can send a message at that time.
I also wonder if its code always runs on the Facebook server, so I can use while loop that always check a time.
I'd appreciate an advice. (I use MongoDB and node)
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var hey = ["Yeah! 😃"]
var reply;
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
app.get("/", function (req, res) {
res.send("Deployed!");
});
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION_TOKEN) {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
app.post('/webhook', function (req, res) {
var data = req.body;
if (data.object === 'page') {
if(d.getHours() === 10 && d.getMinutes() === 5)
sendTextMessage(senderID, "Success!");
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else if(event.postback){
receivedPostback(event);
}
else {
console.log("Webhook received unknown event: ", event);
}
});
});
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
psid = senderID;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
switch (messageText) {
case 'Check':
sendTextMessage(senderID, "isSub: " + isSub);
sendTextMessage(senderID, "gamerNumber: " + gamerNumber);
sendTextMessage(senderID, "psid: " + senderID);
break;
----(and more)
function sendGenericMessage(recipientId, payload) {
var titlee
var subs
var image
switch(payload){
case "pmorning":
titlee = "Breakfast"
subs = //***this is the part where the db value goes in.***
image = "https://cdn.arstechnica.net/wp-content/uploads/sites/3/2016/10/Oculus-Rift-vs-HTC-Vive-vs-PlayStation-VR-1.jpg"
break;
---and more
}]
}]
}
}
}
};
sendTypingOn(recipientId);
callSendAPI(messageData);
}
Take a look at node-cron, which enables you to schedule jobs for running at specific times, specified by a CRON expression

How to upload a file using filesystem I/O in Mean app?

I am using fs for uploading a file in my web app but the console shows that the file has been saved to the desired location which I have entered but the file doesn't show up there.
The code is here:-
var fs = require('fs-extra');
var path = require('path');
module.exports.updatePhoto = function(req,res) {
var file = req.files.file;
var userId = req.body.userId;
console.log("User "+ userId +" is submitting ", file);
var uploadDate = new Date();
var tempPath = file.path;
var targetPath = path.join(__dirname, "../../uploads/" + userId + uploadDate +file.name);
var savePath = "/uploads/" + userId + uploadDate + file.name;
fs.rename(tempPath, targetPath,function(err){
if(err) {
console.log(err);
}
else {
User.findById(userId, function(err, userData){
var user = userData;
user.image = savePath;
user.save(function(err){
if(err) {
console.log("failed")
res.json({status: 500})
}
else {
console.log("saved");
res.json({status: 200})
}
})
})
}
})
};
Are you using connect-multiparty to get the file from Express? https://github.com/expressjs/connect-multiparty
I ended up loading the files to AWS. So the best I can offer is the code to do that. It is basically free for my usage and I use docker to rebuild my site so this make it more flexible.
My File.Js:
'use strict';
module.exports = function (app) {
/**
* Module dependencies.
*/
var auth = require('../config/auth'),
api = {},
multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty(),
path = require('path'),
uuid = require('node-uuid'),
fs = require('fs'),
S3FS = require('s3fs');
var s3fsImpl = new S3FS('FOLDER_NAME_ENTER_HERE', {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});
/**
* Saves the logo file to the server
*/
api.uploadImage = function(req, res) {
// We are able to access req.files.file thanks to the multiparty middleware
var folder = req.params.folder;
var file = req.files.file;
var filename = uuid.v4() + path.extname(file.name);
var stream = fs.createReadStream(file.path);
s3fsImpl.writeFile(folder + '/' + filename, stream).then(function () {
fs.unlink(file.path, function (err) {
if (err) {
console.error(err);
}
});
return res.status(200).json({'fileName': filename, 'url': 'https://s3-us-west-2.amazonaws.com/AWS_FOLDER_ENTER_HERE' + folder + '/' + filename});
});
};
/**
* Routes
*/
app.route('/api/files/:folder/uploadImage')
.post(auth.jwtCheck, multipartyMiddleware, api.uploadImage);
};

Zipping multiple files in Nodejs having size ~ 300kb each and streaming to client

My code is working fine when I zip 3 files around 300kb each and send it to client. Used following links for help:
Dynamically create and stream zip to client
how to convert multiple files to compressed zip file using node js
But as soon as I try to zip 4th file I get "download - Failed Network error" in chrome.
Following is my code:
var express = require('express');
var app = express();
var fileSystem = require('fs');
var Archiver = require('archiver');
var util = require('util');
var AdmZip = require('adm-zip');
var config = require('./config');
var log_file = fileSystem.createWriteStream(__dirname + '/debug.log', {flags : 'a'});
logError = function(d) { //
log_file.write('[' + new Date().toUTCString() + '] ' + util.format(d) + '\n');
};
app.get('/zip', function(req, res, next) {
try {
res = setHeaderOfRes(res);
sendZip(req, res);
}catch (err) {
logError(err.message);
next(err); // This will call the error middleware for 500 error
}
});
var setHeaderOfRes = function (res){
res.setHeader("Access-Control-Allow-Origin", "*"); //Remove this when this is on production
res.setHeader("Content-Type", "application/zip");
res.setHeader("Content-disposition", "attachment;");
return res;
};
var sendZip = function (req, res) {
var filesNotFound = [];
zip.pipe(res);
if (req.query.leapIds) {
var leapIdsArray = req.query.leapIds.split(',');
var i, lengthi;
for (i = 0, lengthi = leapIdsArray.length; i < lengthi; i++) {
try {
var t = config.web.sharedFilePath + leapIdsArray[i] + '.vsdx';
if (fileSystem.statSync(t).isFile()) {
zip.append(new fileSystem.createReadStream(t), {
name: leapIdsArray[i] + '.vsdx'
});
};
} catch (err) {
filesNotFound.push(leapIdsArray[i] + '.vsdx');
}
}
var k, lengthk;
var str = '';
for (k = 0, lengthk = filesNotFound.length; k < lengthk; k++) {
str += filesNotFound[k] +',';
}
if(filesNotFound.length > 0){
zip.append('These file/files does not exist on server - ' + str , { name: 'logFile.log' });
}
zip.finalize();
}
};
I tried zip.file instead of zip.append that didn't work.
I want to zip minimum 10 files of 300kb each and send it to the client. Can anyone please let me know the approach.
Thanks
/********************* Update ****************************************
I was only looking at server.js created in node. Actually the data is sent correctly to client. Angularjs client code seems to be not working for large files.
$http.get(env.nodeJsServerUrl + "zip?leapIds=" + nodeDetails, { responseType: "arraybuffer" }
).then(function (response) {
nodesDetails = response.data;
var base64String = _arrayBufferToBase64(nodesDetails);
function _arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:application/zip;base64,' + base64String,
target: '_blank',
download: $scope.main.routeParams.sectorId + "-ProcessFiles.zip"
})[0].click();
});
This part href: 'data:application/zip;base64,' + base64String, seems to be failing for large data received from server. For small files it is working. Large files it is failing.
Found out.
The problem was not in nodejs zipping logic. That worked perfect.
Issue was in the way I was handling the received response data.
If the data that is received is too large then following code fails
anchor.attr({
href: 'data:application/zip;base64,' + base64String,
target: '_blank',
download: $scope.main.routeParams.sectorId + "-ProcessFiles.zip"
})[0].click();
so the work around is to use blob:
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
var contentType = 'application/zip'
var blob = b64toBlob(base64String, contentType);
saveAs(blob, "hello world.zip");
This link helped me out: How to save binary data of zip file in Javascript?
already answered here: https://stackoverflow.com/a/62639710/8612027
Sending a zip file as binary data with expressjs and node-zip:
app.get("/multipleinzip", (req, res) => {
var zip = new require('node-zip')();
var csv1 = "a,b,c,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
zip.file('test1.file', csv1);
var csv2 = "z,w,x,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
zip.file('test2.file', csv2);
var csv3 = "q,w,e,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
zip.file('test3.file', csv3);
var csv4 = "t,y,u,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
zip.file('test4.file', csv4);
var data = zip.generate({base64:false,compression:'DEFLATE'});
console.log(data); // ugly data
res.type("zip")
res.send(new Buffer(data, 'binary'));
})
Creating a download link for the zip file. Fetch data and convert the response to an arraybuffer with ->
//get the response from fetch as arrayBuffer...
var data = response.arrayBuffer();
const blob = new Blob([data]);
const fileName = `${filename}.${extension}`;
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, fileName);
} else {
const link = document.createElement('a');
// Browsers that support HTML5 download attribute
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}

API using mean stack application

I have installed the new mean app and i want to add an api using that app. I have done some changes in server.js file i add the app.use and body parser to it to get data in json and included the route and the model and the mogodb database.
This is my server.js
'use strict';
/*
var cl = console.log;
console.log = function(){
console.trace();
cl.apply(console,arguments);
};
*/
process.env.NODE_CONFIG_DIR = './config/env';
// Requires meanio .
var mean = require('meanio');
var cluster = require('cluster');
var deferred = require('q').defer();
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use('/api', require('./web/api'));
// Code to run if we're in the master process or if we are not in debug mode/ running tests
if ((cluster.isMaster) &&
(process.execArgv.indexOf('--debug') < 0) &&
(process.env.NODE_ENV!=='test') && (process.env.NODE_ENV!=='development') &&
(process.execArgv.indexOf('--singleProcess')<0)) {
//if (cluster.isMaster) {
console.log('for real!');
// Count the machine's CPUs
var cpuCount = process.env.CPU_COUNT || require('os').cpus().length;
// Create a worker for each CPU
for (var i = 0; i < cpuCount; i += 1) {
console.log ('forking ',i);
cluster.fork();
}
// Listen for dying workers
cluster.on('exit', function (worker) {
// Replace the dead worker, we're not sentimental
console.log('Worker ' + worker.id + ' died :(');
cluster.fork();
});
// Code to run if we're in a worker process
} else {
var workerId = 0;
if (!cluster.isMaster)
{
workerId = cluster.worker.id;
}
// Dependencies
// Creates and serves mean application
mean.serve({ workerid: workerId /* more options placeholder*/ }, function (app) {
var config = app.getConfig();
var port = config.https && config.https.port ? config.https.port : config.http.port;
console.log('Mean app started on port ' + port + ' (' + process.env.NODE_ENV + ') cluster.worker.id:', workerId);
deferred.resolve(app);
});
}
module.exports = deferred.promise;
But when i run the localhost:3000/api/products it redirect me to the home page ie localhost:3000.
Thanks in advance.
api.js
// Dependencies
var express = require('express');
var router = express.Router();
// Models
var Product = require('./models/product');
// Routes
Product.methods(['get', 'put', 'post', 'delete']);
Product.register(router, '/products');
// Return router
module.exports = router;
model/product.js
// Dependencies
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
sku: String,
price: Number
});
// Return model
module.exports = restful.model('Products', productSchema);
It doesn't look like you are connecting your Mongo database in your server.js file and that may be the cause of your issues. Try adding the following line after var app = express;:
mongoose.connect("mongodb://localhost/resources");
Note that resources would be the name of your MongoDB database.

Upload image using file-transfer cordova plugin for android into server (Codeigniter)

I am new in ionic, and Im having a hard time creating a function that could upload an image from photolibrary and even in camera. I have test it using phonegap.I am using ionic framework and using Cordova File-transfer. The function in opening photolibrary and camera works well, but I dont know how to save it into my server (CI) using http POST. Please Help..
This is my Controller :
$scope.selectPicture = function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
};
$cordovaCamera.getPicture(options).then(
function(imageURI) {
window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
$scope.picData = fileEntry.nativeURL;
$scope.ftLoad = true;
var image = document.getElementById('myImage');
image.src = fileEntry.nativeURL;
});
$ionicLoading.show({template: 'Foto acquisita...', duration:500});
},
function(err){
$ionicLoading.show({template: 'Errore di caricamento...', duration:500});
})
};
$scope.uploadPicture = function() {
$ionicLoading.show({template: 'Sto inviando la foto...'});
var fileURL = $scope.picData;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = true;
var params = {};
params.value1 = "someparams";
params.value2 = "otherparams";
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://www.yourdomain.com/upload.php"), viewUploadedPictures, function(error) {$ionicLoading.show({template: 'Errore di connessione...'});
$ionicLoading.hide();}, options);
}
var viewUploadedPictures = function() {
$ionicLoading.show({template: 'Sto cercando le tue foto...'});
server = "http://www.yourdomain.com/upload.php";
if (server) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
else { $ionicLoading.show({template: 'Errore durante il caricamento...', duration: 1000});
return false;
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send()} ;
$ionicLoading.hide();
}`
I just see this code in google and I try. fortunately the function in opening library and camera works. the only problem is I dont know how to save the image into the server(CI)..

Resources