How to generate json output through cucumberjs - json

I am quite new to cucumberjs and javascript, trying to generate a json output. Have created a hook:
have the following in my JsonOutputHook.js
module.exports = function JsonOutputHook() {
try {
var Cucumber = require('cucumber');
var JsonFormatter = Cucumber.Listener.JsonFormatter();
var fs = require('fs');
JsonFormatter.log = function (json) {
fs.writeFile('./cucumber.json', json, function (err) {
if (err) throw err;
});
};
this.registerListener(JsonFormatter);
}
catch(err){
console.log('entered hook exception);
}
};
And following in my world.js
var hooks = require('./JsonOutputHook');
//calling it like this
hooks.call(this);
But on doing so, it throws the following error:
[TypeError: this.registerListener is not a function]
Not sure why am getting this error, also how should I call the hook through my world.js.
Suggestion please.
Thanks
Simit

I'm not sure but I think it's exactly as it means. That function 'registerListener' doesn't exist. Did you write that method? because it's bind to your JsonOutputHook. You could also check /cucumber/lib/listener to see if that method is there. Also if you are use atom as a text editor you can search the project for that method.(I'm pretty sure other text editors might have this feature as well). As for how you can call the hook that should be in the marvelous documentation found on their git repo (https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/hooks.md).

Related

How to use callbacks in module.export function for mysql query - nodejs,express

I have the following code structure in exports.js
module.exports = {
getData:function(param1,param2,callback){
sql.query('SELECT users FROM table',function(error,result){
callback(null,result[0]);
});
}
}
And I called it from main file app.js file like
var common = require('./exports');
console.log(common.getData(null,null));
I got the following error
TypeError: callback is not a function
However I found a similar question here. But didn't fixed the problem. Any help would be appreciated..!
if you want print results
var common = require('./exports');
common.getData(null, null, function(err, result){
console.log(result)l
})
getData() accepts 3 arguments
The last of which should be a function which you have not provided in your example. Add a callback function in your call like so:
common.getData(null,null, function(err, result) {
console.log(result)
});
The sql.query function uses the callback function you pass in as the third parameter and thats why your getting the error to say it's missing.

synchronous mysql queries in nodejs

I'm pretty new to nodejs and I'm having some difficulties to understand how to use the mysql connection object.
My problem is not in the code but in the design pattern.
lets say I have a user module
module.exports = function(){
return{
id: "",
load: function(id){
var sql = 'SELECT * from users where id = '+ DB.escape(id);
console.log(1);
DB.query(sql, function (err, rows) {
this.id = rows[0].id; // not working
console.log(rows[0].id); // prints the id 4
console.log(2);
});
console.log(3);
}
}
}
from outside the module i run the next code
var user = require('../modules/user');
var selected_user = user();
console.log("entering users me route");
selected_user.load(4);
console.log("user id is " + selected_user.id); //This does not print the id 4
when I run the code, the console logs 1, then 3, and then 2.
This is due to the asynchronous flow of node js.
But if I'm building a website, and I need the query to end in order to populate my user object before I send the HTML to the browser???
What's the right way to do it ?
Also when I try to populate the id property of user in the id i receive from the DB it does not work.
Any ideas?
Thanks
There are several ways to do this. I would go with Promises.
Suppose you have an asynchronous function "getUsers".
It looks like this:
function getUsers() {
longQuery(function(err, result){
// What to do with result?
});
You need to rewrite it to be able to use the result.
Let's try:
function getUsers() {
return new Promise(function(resolve, reject) {
longQuery(function(err, result){
if(err) reject(err)
else resolve(result)
});
});
Now this function returns a promise. What do we do with that promise?
function handleRequest(req, res) {
getUsers().then(function(result) {
// Do stuff with result
res.send(myProcessedData);
}).catch(function(err) {console.log(err)};
}
This could also have been done with callbacks, passing the response object as a parameter to the query function, and many other ways, but I think promises are a very elegant way for handling this.
this.id = rows[0].id; // not working
The above line is not working because you are setting it to this.id from inside a callback function. When you are inside a callback function this does not mean the this in the main object.
For more discussion about this: see How to access the correct `this` context inside a callback?
To tackle the asynchronous nature of javascript you can either use promise like the answer from matanso or you can pass a callback function to your load method. So your load: function(id) method will be load: function(id, callbackFunction) and call the callback function when you get all the data that you need.

How can I use ngCordova File api to save JSON?

I'm trying to save JSON data in my Ionic app to the local device storage. I would like to use the ngCordova File plugin. I can't seem to find any tutorials or example apps that use the exact methods they have in the docs.
Has anyone used this plugin before to save JSON data? How did you do it?
ngCordova takes away a lot of the ugliness of writing files using the file writer API.
This example has been adapted from the docs, and uses writeFile(path, file, data, replace) where the path is defined by cordova.file.DIRECTORY_TYPE, file is a string name for the file, data is the string representation of the data (so we will use JSON.stringify()). Replace is a boolean that will simply erase the existing contents of the file.
//Write using cordova.file.dataDirectory, see File System Layout section for more info
var json = {"test": "hello world"}
$cordovaFile.writeFile(cordova.file.dataDirectory, "hello.json", JSON.stringify(json), true)
.then(function (success) {
// success
}, function (error) {
// error
console.log(error); //error mappings are listed in the documentation
});
For a controller, supposing we are using controllerAs syntax it could look something like this:
angular.controller("...",['$cordovaFile' function ($cordovaFile) {
var vm = this;
vm.writeFile = function (fileName) {
ionic.Platform.ready(function(){
// will execute when device is ready, or immediately if the device is already ready.
var json = {"test": "hello world"}
$cordovaFile.writeFile(cordova.file.dataDirectory, "hello.json", JSON.stringify(json), true)
.then(function (success) {
// success
}, function (error) {
// error
console.log(error); //error mappings are listed in the documentation
});
});
};
});

Meteor-Down: Cant assign new instance to mdown variable - undefined is not a function

I try to include meteor down into my application like the telescope example:
https://gist.github.com/mnmtanish/fe4f7efb3db24e83c310
var mdown = new MeteorDown(function(error, client){
//code block
});
My console tells me:
Uncaught TypeError: undefined is not a function
meteor list
meteorhacks:meteor-down 1.1.1 Load Testing Framework for Meteor
Looks like shortly after that gist was posted the API had changed. If you look at this commit: https://github.com/meteorhacks/meteor-down/commit/7791be3a912f37c5a7cf82a230344fb1f761edcd
- var mdown = new MeteorDown(function (error, client) {
- client.call('add', x, y, function (err, res) {
was removed. It looks like meteorDown is now what you want to use. I would suggest looking through the Meteor Down documentation for the latest usage of the API
Specifically the Readme shows the new way to handle this below:
meteorDown.init(function (Meteor) {
Meteor.call('example-method', function (error, result) {
Meteor.kill();
});
});
meteorDown.run({
concurrency: 10,
url: "http://localhost:3000"
});

LocomotiveJS access response JSON in controller's after filter

I'm looking for a way to access the JSON being sent back to the requestor in the "after" filter for a controller.
var locomotive = require('locomotive');
var myController = new locomotive.Controller();
myController.after('myAction', function(next) {
var response = {}; //I want to access the JSON being sent back in myAction: {'hello':'world'}
console.log(response); //this should log "{'hello':'world'}"
next();
});
myController.myAction = function myAction() {
this.res.json({'hello':'world'});
}
module.exports = myController;
If anyone has any way of doing this, it would be much appreciated.
In your main action, assign your json to an object on this (res is reserved):
myController.myAction = function myAction() {
this.model = {'hello':'world'};
this.res.json(this.model);
}
Then you can access it in your after filter:
myController.after('myAction', function(next) {
var model = this.model;
console.log(model);
next();
});
I found a "hack" solution... It's not the cleanest, and requires changing the code within the express response.js file in "node_modules"...
If anyone has a better option where you can access the json being sent in response to the request within the controller action (or controller filter) itself, I'd greatly appreciate it.
Thanks.
in the ~/node_modules/locomotive/node_modules/express/lib/response.js file, I altered the "res.json" function (line 174 for me) to include the following line after the declaration of the body variable (which is passed to the send function).
this.responseJSON = body;
This allows you to access this.responseJSON within a controller's after filter, as follows:
myController.after('myAction', function(next) {
**var response = this.res.responseJSON; //ACCESS RESPONSE JSON HERE!!!!!**
console.log(response); //Now logs "{'hello':'world'}"
next();
});
Like I said, not the most elegant, but gets the job done in a pinch. Any more elegant solutions welcome...