Protractor test case freezes when run on bamboo - node.js

When I run my test on Visual studio my test runs successfully. But when I try to run it on bamboo my browser freezes and my test fails with the jasmine timeout exception.
Please find my protractor conf file :
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporters = require('jasmine-reporters');
var co = require('co');
// Example usage:
// protractor --env=local
// protractor --env=local --specs=test/road/road-missing.js
var reporter = new HtmlScreenshotReporter({
dest: 'target/screenshots',
filename: 'Test_Report.html',
fixedScreenshotName: true
});
var junitReporter = new reporters.JUnitXmlReporter({
savePath: 'target/screenshots',
consolidateAll: false
});
var customReporter = {
specStarted: function(result) {
console.log('\n---------------- Spec started: ' + result.fullName + ' ----------------');
}
}
var FUNCTION_CONFIG = {
beforeLaunch: function () {
return new Promise(function (resolve) {
reporter.beforeLaunch(resolve);
});
},
onPrepare: function () {
// cleanup of a failed test, generating an alert: "You have unsent changes."
// This will log the error:
// UnexpectedAlertOpenError: unexpected alert open: {Alert text : You have unsent changes.}
afterEach(co.wrap(function*() {
browser.ignoreSynchronization = true;
// force leaving page by open page about:blank
yield browser.get("about:blank");
try {
// if no alert is shown an exception is thrown. This is the case if a test finished successful
var alert = yield browser.switchTo().alert();
yield alert.accept();
} catch (e) {
// case: no alert was shown. accessing alert will trhow an exception, which can be ignored
}
}));
browser.manage().window().setSize(480, 900);
jasmine.getEnv().addReporter(reporter);
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'target/screenshots',
filePrefix: 'xmloutput'
}));
jasmine.getEnv().addReporter(customReporter);
},
afterLaunch: function (exitCode) {
return new Promise(function (resolve) {
reporter.afterLaunch(resolve.bind(this, exitCode));
});
}
};
function extend(obj, source) {
if (source) {
for (var prop in source) {
if (typeof obj[prop] === "object" && !Array.isArray(obj[prop]))
extend(obj[prop], source[prop]);
else
obj[prop] = source[prop];
}
}
return obj;
};
function getArgv(parameter) {
var argv = process.argv;
var param = parameter + "=";
for (var i = 0; i < argv.length; i++) {
if (argv[i].startsWith(parameter))
return argv[i].substring(param.length);
}
return undefined;
}
var DEFAULT_CONFIG = require('./env/default.js');
var env = getArgv('--env') || 'local';
var ENV_CONFIG = require('./env/' + env + '.js');
var conf = extend(FUNCTION_CONFIG, DEFAULT_CONFIG);
exports.config = extend(
conf,
ENV_CONFIG
);
Also this is one of the test case which fails on browser :
var UI = require('./../ui.js');
var co = require('co');
var ui = new UI();
describe("MapFeedback: address-infowrong", function () {
ui.setSmallScreenSize();
// ui.testLogger(100);
it("test", co.wrap(function* () {
yield browser.get(ui.createAddressStartLink());
yield ui.ADDRESS_PROBLEM.click();
var version = yield browser.executeScript('return mapfeedbackVersion');
console.log("Map feedback Version:" + version);
expect(browser.getCurrentUrl()).toContain("report_address");
yield ui.ADDRESS_INFO_WRONG.click();
expect(browser.getCurrentUrl()).toContain("select_address_edit/address_edit");
yield ui.zoomIn(18.5);
var elmOK = element(By.css('button[ng-click="doneSelectObject(selectedObject)"]'));
yield ui.waitFor(protractor.ExpectedConditions.elementToBeClickable(elmOK));
yield elmOK.click();
expect(browser.getCurrentUrl()).toContain("address_edit");
yield element(by.xpath("/html/body/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/input")).click();
yield element(by.xpath("//*[#id=\"input_addressNumber\"]")).sendKeys("TEST");
yield element(by.xpath(" /html/body/div[1]/div/div/div[2]/div[2]/div[4]/div[1]/input")).click();
yield element(by.xpath("//*[#id=\"input_address_other\"]")).sendKeys("TEST");
yield ui.SUBMIT.click();
expect(browser.getCurrentUrl()).toContain("submit");
yield ui.waitSubmit();
var reportId = yield browser.executeScript('return mapFeedBack.reportId');
console.log("address-infowrong id: " + reportId);
expect(yield element(By.css('div[ng-show="mapFeedBack.submitState==\'success\'"]')).isDisplayed()).toBeTruthy();
var req = yield ui.getMapFeedbackData(-reportId);
var body = JSON.parse(req.body);
console.log(body);
expect(body.properties.error).toEqual(21);
expect(body.properties.details).toEqual("Other address issue: TEST");
}));
});
Note : I am using a selenium grid for my test automation.
// --- config: default
module.exports = {
params: {
baseUrl: "NOT-SET",
urlParams: "zoomLevel=15",
urlParamCoords: "55.67653,12.56040", // Copanhagen Location
urlAddressParamCoords: "40.75170,-73.99420", //New York Location,
rest: {
baseUrl: "NOT-SET",
header: {
// 'Content-Type': 'application/vnd.here.layerObjectList+json; charset=UTF-8',
'Auth-Identifier': 'Y-7Wnc2lNk3fMI0n3-rZ',
'Auth-Secret': 'mEv_DZ1JKDDYzESUAp9KyQ',
'Auth-Service-Id': 'here_app',
'User-Agent': 'mapfeedback-test',
'Accept': 'application/vnd.here.layerObject+json',
'Group-Id': 'FGx1AWaAzKOo0imNkLmf'
}
}
},
seleniumAddress: "http://selenium.community.nw.ops.here.com:4444/wd/hub",
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
maxInstances: 1
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directly when protractor is called.
specs: [
// Note: group & sort tests by feature
'./test/address/address-remove.js',
'./test/address/address-missing.js',
'./test/address/address-infowrong.js',
'./test/border/border-linemissing.js',
'./test/border/border-linedrawnwrong.js',
'./test/other/other-cartoincorrect.js',
'./test/other/other-cartomissing.js',
'./test/other/other-cartoremove.js',
'./test/place/place-closed.js',
'./test/place/place-offensivecontent.js',
'./test/place/place-violateprivacy.js',
'./test/place/place-Inappropriatebehaviour.js',
'./test/place/place-otherviolation.js',
'./test/place/place-copyright.js',
'./test/place/place-otherissue.js',
'./test/place/place-missing.js',
'./test/place/place-infowrong.js',
'./test/road/road-missing.js',
'./test/road/road-closed.js',
'./test/road/road-infowrong.js',
'./test/satellite/satellite-conflictimage.js',
'./test/satellite/satellite-obscuredimage.js',
'./test/satellite/satellite-oldimage.js',
'./test/satellite/satellite-unclearimage.js',
],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 50000
}
};
Please help ??

Related

Alexa Test Response does not contain outputSpeech

I'm new to Alexa, and have followed the airportinfo tutorial and I have copied the code from github https://github.com/bignerdranch/alexa-airportinfo and when i test it using npm and input an airport code e.g. SFO, Theres no "outputSpeech:" and i tried making a similar skill with the same issue, I'm not sure what I'm doing wrong. I have both index.js and FAADataInfo.js Thanks in advance for your help.
This is the index.js file
'use strict';
module.change_code = 1;
var _ = require('lodash');
var Alexa = require('alexa-app');
var skill = new Alexa.app('airportinfo');
var FAADataHelper = require('./faa_data_helper');
skill.launch(function(req, res) {
var prompt = 'For delay information, tell me an Airport code.';
res.say(prompt).reprompt(prompt).shouldEndSession(false);
});
skill.intent('airportInfoIntent', {
'slots': {
'AIRPORTCODE': 'FAACODES'
},
'utterances': [
'{|flight|airport} {|delay|status} {|info} {|for} {-|AIRPORTCODE}'
]
},
function(req, res) {
var airportCode = req.slot('AIRPORTCODE');
var reprompt = 'Tell me an airport code to get delay information.';
if (_.isEmpty(airportCode)) {
var prompt = 'I didn\'t hear an airport code. Tell me an airport code.';
res.say(prompt).reprompt(reprompt).shouldEndSession(false);
return true;
} else {
var faaHelper = new FAADataHelper();
console.log(airportCode);
faaHelper.getAirportStatus(airportCode).then(function(airportStatus) {
console.log(airportStatus);
res.say(faaHelper.formatAirportStatus(airportStatus)).send();
}).catch(function(err) {
console.log(err.statusCode);
var prompt = 'I didn\'t have data for an airport code of ' +
airportCode;
res.say(prompt).reprompt(reprompt).shouldEndSession(false).send();
});
return false;
}
}
);
module.exports = skill;
and heres FAADataInfo.js
'use strict';
var _ = require('lodash');
var requestPromise = require('request-promise');
var ENDPOINT = 'http://services.faa.gov/airport/status/';
function FAADataHelper() {
}
FAADataHelper.prototype.getAirportStatus = function(airportCode) {
var options = {
method: 'GET',
uri: ENDPOINT + airportCode,
json: true
};
return requestPromise(options);
};
FAADataHelper.prototype.formatAirportStatus = function(aiportStatusObject) {
if (aiportStatusObject.delay === 'true') {
var template = _.template('There is currently a delay for ${airport}. ' +
'The average delay time is ${delay_time}.');
return template({
airport: aiportStatusObject.name,
delay_time: aiportStatusObject.status.avgDelay
});
} else {
//no delay
var template =_.template('There is currently no delay at ${airport}.');
return template({
airport: aiportStatusObject.name
});
}
};
module.exports = FAADataHelper;
This is the response that I get
{
"version": "1.0",
"response": {
"directives": [],
"shouldEndSession": true
},
"sessionAttributes": {},
"dummy": "text"
}
The alexa-app version that the tutorial is using is out of date. When using the latest alexa-app npm version (4.0.0), the return value for the .intent() function should be a Promise and not a boolean if you are running asynchronous functions.
In your index.js, add:
return faaHelper.getAirportStatus(....) {}.catch(){}
and remove the return false; after the catch.
Here's the full skill.intent() code
skill.intent('airportInfoIntent', {
'slots': {
'AIRPORTCODE': 'FAACODES'
},
'utterances': [
'{|flight|airport} {|delay|status} {|info} {|for} {-|AIRPORTCODE}'
]
},
function(req, res) {
var airportCode = req.slot('AIRPORTCODE');
var reprompt = 'Tell me an airport code to get delay information.';
if (_.isEmpty(airportCode)) {
var prompt = 'I didn\'t hear an airport code. Tell me an airport code.';
res.say(prompt).reprompt(reprompt).shouldEndSession(false);
return true;
} else {
var faaHelper = new FAADataHelper();
console.log(airportCode);
return faaHelper.getAirportStatus(airportCode).then(function(airportStatus) {
console.log(airportStatus);
res.say(faaHelper.formatAirportStatus(airportStatus)).send();
}).catch(function(err) {
console.log(err.statusCode);
var prompt = 'I didn\'t have data for an airport code of ' +
airportCode;
res.say(prompt).reprompt(reprompt).shouldEndSession(false).send();
});
//return false;
}
}
);

Using Babel to Get ApolloClient to ES5 CommonJS Module Format for Node Environment

Using Babel to Get ApolloClient to ES5 CommonJS Module Format
Im trying to use Babel to get the apollo-client module to work as ES5 in a non-browser, node environment. I've gone through step below which always give me the same result. Im trying to figure out if that result is right result for a node environment. When I import the babel processed documents into my project and call a method that should be exported, im getting, cannot find module. For context, the project is a fusetools.com demo. Fusetools does not support ES2015 Promises so the idea is that with the babel es2015 preset, it should work. I'm mostly chasing this down to learn something but it would be great if I could get it to work. Any comments on an easier way to do this, now that I understand it better, would be greatly appreciated. The project where I babeled the code can be found here. The fusetools project where i used the transformed code is here.
The error I get is :
LOG: Error: JavaScript error in MainView.ux line 9: Name: Fuse.Scripting.Error
Error message: require(): module not found: js/apollo-client/ApolloClient.js
File name: MainView.ux
Line number: 9
Source line: var ApolloClient = require('js/apollo-client/ApolloClient.js');
This is the code im trying to reach:
```
"use strict";
var networkInterface_1 = require('./transport/networkInterface');
var isUndefined = require('lodash.isundefined');
var assign = require('lodash.assign');
var isString = require('lodash.isstring');
var store_1 = require('./store');
var QueryManager_1 = require('./core/QueryManager');
var storeUtils_1 = require('./data/storeUtils');
var fragments_1 = require('./fragments');
var getFromAST_1 = require('./queries/getFromAST');
var DEFAULT_REDUX_ROOT_KEY = 'apollo';
function defaultReduxRootSelector(state) {
return state[DEFAULT_REDUX_ROOT_KEY];
}
var ApolloClient = function () {
function ApolloClient(_a) {
var _this = this;
var _b = _a === void 0 ? {} : _a,
networkInterface = _b.networkInterface,
reduxRootKey = _b.reduxRootKey,
reduxRootSelector = _b.reduxRootSelector,
initialState = _b.initialState,
dataIdFromObject = _b.dataIdFromObject,
resultTransformer = _b.resultTransformer,
resultComparator = _b.resultComparator,
_c = _b.ssrMode,
ssrMode = _c === void 0 ? false : _c,
_d = _b.ssrForceFetchDelay,
ssrForceFetchDelay = _d === void 0 ? 0 : _d,
_e = _b.mutationBehaviorReducers,
mutationBehaviorReducers = _e === void 0 ? {} : _e,
_f = _b.addTypename,
addTypename = _f === void 0 ? true : _f,
queryTransformer = _b.queryTransformer;
this.middleware = function () {
return function (store) {
_this.setStore(store);
return function (next) {
return function (action) {
var returnValue = next(action);
_this.queryManager.broadcastNewStore(store.getState());
return returnValue;
};
};
};
};
if (reduxRootKey && reduxRootSelector) {
throw new Error('Both "reduxRootKey" and "reduxRootSelector" are configured, but only one of two is allowed.');
}
if (reduxRootKey) {
console.warn('"reduxRootKey" option is deprecated and might be removed in the upcoming versions, ' + 'please use the "reduxRootSelector" instead.');
this.reduxRootKey = reduxRootKey;
}
if (queryTransformer) {
throw new Error('queryTransformer option no longer supported in Apollo Client 0.5. ' + 'Instead, there is a new "addTypename" option, which is on by default.');
}
if (!reduxRootSelector && reduxRootKey) {
this.reduxRootSelector = function (state) {
return state[reduxRootKey];
};
} else if (isString(reduxRootSelector)) {
this.reduxRootKey = reduxRootSelector;
this.reduxRootSelector = function (state) {
return state[reduxRootSelector];
};
} else if (typeof reduxRootSelector === 'function') {
this.reduxRootSelector = reduxRootSelector;
} else {
this.reduxRootSelector = null;
}
this.initialState = initialState ? initialState : {};
this.networkInterface = networkInterface ? networkInterface : networkInterface_1.createNetworkInterface({ uri: '/graphql' });
this.addTypename = addTypename;
this.resultTransformer = resultTransformer;
this.resultComparator = resultComparator;
this.shouldForceFetch = !(ssrMode || ssrForceFetchDelay > 0);
this.dataId = dataIdFromObject;
this.fieldWithArgs = storeUtils_1.storeKeyNameFromFieldNameAndArgs;
if (ssrForceFetchDelay) {
setTimeout(function () {
return _this.shouldForceFetch = true;
}, ssrForceFetchDelay);
}
this.reducerConfig = {
dataIdFromObject: dataIdFromObject,
mutationBehaviorReducers: mutationBehaviorReducers
};
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.setStore = this.setStore.bind(this);
this.resetStore = this.resetStore.bind(this);
}
ApolloClient.prototype.watchQuery = function (options) {
this.initStore();
if (!this.shouldForceFetch && options.forceFetch) {
options = assign({}, options, {
forceFetch: false
});
}
fragments_1.createFragment(options.query);
var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
var realOptions = Object.assign({}, options, {
query: fullDocument
});
delete realOptions.fragments;
return this.queryManager.watchQuery(realOptions);
};
;
ApolloClient.prototype.query = function (options) {
this.initStore();
if (!this.shouldForceFetch && options.forceFetch) {
options = assign({}, options, {
forceFetch: false
});
}
fragments_1.createFragment(options.query);
var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
var realOptions = Object.assign({}, options, {
query: fullDocument
});
delete realOptions.fragments;
return this.queryManager.query(realOptions);
};
;
ApolloClient.prototype.mutate = function (options) {
this.initStore();
var fullDocument = getFromAST_1.addFragmentsToDocument(options.mutation, options.fragments);
var realOptions = Object.assign({}, options, {
mutation: fullDocument
});
delete realOptions.fragments;
return this.queryManager.mutate(realOptions);
};
;
ApolloClient.prototype.subscribe = function (options) {
this.initStore();
var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
var realOptions = Object.assign({}, options, {
document: fullDocument
});
delete realOptions.fragments;
delete realOptions.query;
return this.queryManager.startGraphQLSubscription(realOptions);
};
ApolloClient.prototype.reducer = function () {
return store_1.createApolloReducer(this.reducerConfig);
};
ApolloClient.prototype.initStore = function () {
if (this.store) {
return;
}
if (this.reduxRootSelector) {
throw new Error('Cannot initialize the store because "reduxRootSelector" or "reduxRootKey" is provided. ' + 'They should only be used when the store is created outside of the client. ' + 'This may lead to unexpected results when querying the store internally. ' + "Please remove that option from ApolloClient constructor.");
}
this.setStore(store_1.createApolloStore({
reduxRootKey: DEFAULT_REDUX_ROOT_KEY,
initialState: this.initialState,
config: this.reducerConfig
}));
this.reduxRootKey = DEFAULT_REDUX_ROOT_KEY;
};
;
ApolloClient.prototype.resetStore = function () {
this.queryManager.resetStore();
};
;
ApolloClient.prototype.setStore = function (store) {
var reduxRootSelector;
if (this.reduxRootSelector) {
reduxRootSelector = this.reduxRootSelector;
} else {
reduxRootSelector = defaultReduxRootSelector;
this.reduxRootKey = DEFAULT_REDUX_ROOT_KEY;
}
if (isUndefined(reduxRootSelector(store.getState()))) {
throw new Error('Existing store does not use apolloReducer. Please make sure the store ' + 'is properly configured and "reduxRootSelector" is correctly specified.');
}
this.store = store;
this.queryManager = new QueryManager_1.QueryManager({
networkInterface: this.networkInterface,
reduxRootSelector: reduxRootSelector,
store: store,
addTypename: this.addTypename,
resultTransformer: this.resultTransformer,
resultComparator: this.resultComparator,
reducerConfig: this.reducerConfig
});
};
;
return ApolloClient;
}();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ApolloClient;
//# sourceMappingURL=ApolloClient.js.map
```
Any and all comments I might learn from are appreciated. Thank you.
One way to do this would be to use webpack like this:
const webpack = require('webpack');
const path = require('path');
module.exports = {
// watch: true,
entry: {
ApolloClient: './config/ApolloClient.js',
createNetworkInterface: './config/createNetworkInterface.js',
Redux: './config/Redux.js',
},
output: {
path: path.join(__dirname, 'build/Libs'),
filename: '[name].js',
library: '[name]',
libraryTarget: 'commonjs',
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
Then in config directory you could have:
/* ApolloClient.js */
import { ApolloClient } from 'apollo-client';
export default ApolloClient;
and
/* createNetworkInterface.js */
import { createNetworkInterface } from 'apollo-client/transport/networkInterface';
export default createNetworkInterface;
plus if you want to have Redux as well:
/* Redux.js */
import * as Redux from 'redux';
export default Redux;
However I was not able to get gql done this way and had to use bolav's fusepm.
Which you would use exactly as bolav has mention, first install it globally:
npm install -G fusepm and then fusepm npm graphql-tag
Once you have all these in place you can require them as follow:
var Redux = require('build/Libs/Redux');
var ApolloClient = require('build/Libs/ApolloClient');
var createNetworkInterface = require('build/Libs/createNetworkInterface');
var gql = require('fusejs_lib/graphql-tag_graphql-tag.umd');
This way still could use some TLC but for now, it works and get's the job done:
var networkInterface = createNetworkInterface.createNetworkInterface({
uri: 'http://localhost:8000/graphql',
});
var client = new ApolloClient.ApolloClient({
networkInterface,
});
client.query({
query: gql`
query {
allPosts {
edges {
node {
id
headline
summary(length: 80)
body
createdAt
updatedAt
personByAuthorId {
firstName
lastName
}
}
}
}
}
`,
})
.then(data => data.data.allPosts.edges.forEach(node => pages.add(createPage(node))))
.catch(error => console.log(error));
Also if you like I've setup a whole project along with server that might be of an interest to you: fuseR
I made fusepm, which has a mode to convert npm modules to run them under FuseTools. It's still has a lot of bugs, but at least I managed to come longer than you:
fuse create app apolloc
cd apolloc
npm install apollo-client
fusepm npm apollo-client
And then in your javascript:
<JavaScript>
var ApolloClient = require('fusejs_lib/apollo-client.js');
</JavaScript>
fusepm uses Babel, with some custom plugins.

Making jquery ajax call in child process - node.js

I am using 'child_process'(fork method) to handle task of saving some records across server. For this I was using jquery ajax call in the child process to save the records. But somehow that code doesn't get executed.
I have already included the jquery.min.js file in the html in which I am including the file forking child process as well.
The file forking child process:
var childProcess = require('child_process');
var syncProcess;
function launchMindwaveDataSync(){
//alert("launchMindwaveDataSync fired");
var iconSync = document.getElementById("iconSync");
iconSync.src = "images/findDevice.gif";
iconDevice.title = "Synchronizing...";
//Launch the device reader script in a new V8 process.
syncProcess = childProcess.fork('./js/mindwaveDataSync.js');
syncProcess.on('message', function(message){
console.log(message);
switch(message.msg)
{
case "connected":
global.HEADSET_CONNECTED = true;
iconDevice.src = "images/icon-power.png";
iconDevice.title = "Connected to Mindwave Mobile device";
startSynchronizing();
break;
case "disconnected":
case "error":
case "close":
case "timeout":
global.HEADSET_CONNECTED = false;
iconDevice.src = "images/error.png";
iconDevice.title = "Mindwave Mobile device is disconnected";
break;
}
});
syncProcess.on('error', function(e){
console.log(e);
});
setTimeout(function(){
console.log('sending command initialize');
syncProcess.send({cmd:'initialize'});
},1000);
};
function startSynchronizing(){
syncProcess.send({cmd: 'synchronize'});
}
The child process which is supposed to make ajax call
var recursive = require('recursive-readdir');
var SecurConf = require('../js/secureConf');
var sconf = new SecurConf();
var filesToSync = [];
var crypto = require('crypto');
var options = {
//prompt : 'File Password : ',
algo : 'aes-128-ecb',
file : {
encoding : 'utf8',
out_text : 'hex'
}
};
process.on('message', function (command){
console.log(command);
switch(command.cmd)
{
case "initialize": initializeConnection();
break;
case "synchronize": checkForFiles();
break;
case "record":
client.resume();
break;
case "pause":
client.pause();
break;
case "stop":
client.destroy();
break;
}
//process.send({msg:"Sync Process: " + command.cmd});
});
function checkForFiles(){
recursive('C:/MindWaveData/Data/', function (err, files) {
// Files is an array of filename
filesToSync = files;
decryptFiles();
//process.send({msg:files});
});
}
function decryptFiles(){
var ajaxSuccess = function(res){
process.send({msg:res});
}
for(var i = 0; i < filesToSync.length; i++){
var ef = ""+filesToSync[i];
sconf.decryptFile(ef, function(err, file, content){
if(err){
process.send({msg:"some error occurred while decrypting..."});
} else {
var parsedContent = JSON.parse(content);
var decryptedContent = JSON.stringify(parsedContent, null,'\t');
for(var j = 0; j<parsedContent.length; j++){
$.ajax({
//async: false,
type: "POST",
url: "http://192.168.14.27:8001/admin/webservice",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
'ncFunction': 'login',
'ncParams': {
'ncUserEmail': "clarity_admin#yopmail.com",
'ncUserPassword': "cl123!##"
}
}),
success: function (res) {
ajaxSuccess(res);
},
error: function (xhr, type, err) {
ajaxSuccess(res);
}
});
}
});
}
}
function initializeConnection(){
//console.log('initializeConnection::function');
//process.send({msg:"initializeConnection called"});
checkConnection()
//process.send({msg:"connected"});
//call function to send ajax request
}
function checkConnection(){
//console.log('checkConnection::function');
//call ajax request 3 times to check the connection.. once in third try we get the response OK, we can send the process message as connected
var ajaxCallCount = 0;
var makeAjaxCall = function(){
//console.log('function makeAjaxCall');
//process.send({msg:"connected"});
if(ajaxCallCount < 2){
ajaxCallCount++;
//console.log('ajaxCallCount:'+ajaxCallCount);
//process.send({msg:'value of ajaxCallCount:'+ajaxCallCount});
connectionSuccess();
}
else{
process.send({msg:"connected"});
}
};
var connectionSuccess = function(){
//console.log('function connectionSuccess');
makeAjaxCall();
};
makeAjaxCall();
}
Can we use jquery ajax call in the child process like this? Plus I have included the file forking child process in one html file and on load of its body I am calling /launchMindwaveDataSync/ from the first file shown below.
Thanks in advance

Utilising Nodejs Promises (Bluebird) during module loading and configuration

Morning All
I've been scouring S.O. for the past couple of days trying to find an answer I understood/was applicable to my situation, and have now admitted defeat, primarily due to my lack of comprehension around Promises (promise-n00b). So I'm basically putting out a plea for some help with my example posted below. I think it's fairly explanatory what I'm doing but in case it isn't, I'm trying to:
Apply some synchronous config to the server
Load a Logger module and instantiate a new of instance of it as logger, and then run some necessary checks (e.g. do we have a log file?) before returning an indicator to say that it loaded successfully (either a boolean or the logger object itself)
Then pass that logger to the utils (they need it to log)
Finally call the callback passed in by the scripts run by npm start and npm test
Obviously there's a lot more going on in the real world but I'd tried to distil the code down to the bit I don't get, namely the Promise chain.
Finally, as a long term user of callbacks who has never struggled to comprehend them (brain must work differently perhaps) do any of you dudes have any pearls of wisdom likely to cause a lightbulb moment?
Many thanks in advance and yes I know this code as it stands doesn't/won't work ;-)
Code as follows:
server.js
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs-extra'));
var boss = {
start: function(callback) {
var p = new Promise.try(function() {
console.log('start');
})
.then(boss.applyConfig)
.then(boss.startLogger)
.then(function(lggr) {
console.log('logger setup complete: ' + lggr);
boss.logger = lggr;
return lggr;
})
.then(boss.loadUtils)
.finally(function() {
if (callback) callback();
})
.catch(function(err) {
console.log.call(null, '\033[31m' + err.stack + ' \033[39m');
});
},
applyConfig: function() {
console.log('applying config');
return 'config';
},
startLogger: function() {
console.log('starting logger');
var Logger = require('./Logger')(fs, Promise);
var logger = new Logger();
return new Promise(function(resolve, reject) {
var result = logger.init();
if (result) {
resolve(logger);
}
else {
reject(logger);
}
});
},
loadUtils: function(logger) {
console.log('loading utils with ' + logger);
boss.logger.log('loading utils with ' + logger);
return 'utils';
}
};
boss.start(function(){
console.log('done');
});
Logger.js
module.exports = function(fs, Promise) {
var Logger = function(options) {
this.filePath = (options && options.filePath) ? options.filePath : __dirname + '/../log/';
this.filename = (options && options.filename) ? options.filename : 'all.log';
};
Logger.prototype.init = function() {
var logger = this;
console.log('logger.init');
return new Promise(function(resolve) {
new Promise.resolve(logger.checkForLogFile()).then(function(exs) {
console.log('exs', exs);
return exs;
});
})
};
Logger.prototype.log = function(msg) {
// requires that the log file exists and that we have a stream to it (create stream function removed)
console.log.call(null, '\033[36mLogging: ' + msg + ' \033[39m');
};
Logger.prototype.checkForLogFile = function() {
var logger = this;
fs.existsAsync(logger.filePath + logger.filename).then(function (exists) {
console.log('exists', exists);
return exists;
});
};
return Logger;
};
First up - thanks Benjamin :) And secondly, how amazingly surprising that all this would now work within 30 mins of posting on S.O. after a couple of days prior effort ;-)
So yes - golden takeaway nugget is KISS!
Following code now works correctly and logs in the correct order as follows:
start
applying config
starting logger
logger.init
statObj { dev: 2067,
mode: 33204,
...
ctime: Thu Nov 27 2014 11:40:34 GMT+0000 (GMT) }
exists true
logger setup complete: [object Object]
loading utils with [object Object]
Logging: loading utils with [object Object]
done
server.js
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs-extra'));
var boss = {
start: function(callback) {
var p = new Promise.try(function() {
console.log('start');
})
.then(boss.applyConfig)
.then(boss.startLogger)
.then(function(lggr) {
console.log('logger setup complete: ' + lggr);
boss.logger = lggr;
return lggr;
})
.then(boss.loadUtils)
.finally(function() {
if (callback) callback();
})
.catch(function(err) {
console.log.call(null, '\033[31m' + err.stack + ' \033[39m');
});
},
applyConfig: function() {
console.log('applying config');
return 'config';
},
startLogger: function() {
console.log('starting logger');
var Logger = require('./Logger')(fs, Promise);
var logger = new Logger();
return logger.init();
},
loadUtils: function(logger) {
console.log('loading utils with ' + logger);
boss.logger.log('loading utils with ' + logger);
return 'utils';
}
};
boss.start(function(){
console.log('done');
});
Logger.js
module.exports = function(fs, Promise) {
var Logger = function(options) {
this.filePath = (options && options.filePath) ? options.filePath : __dirname + '/../log/';
this.filename = (options && options.filename) ? options.filename : 'all.log';
};
Logger.prototype.init = function() {
var logger = this;
console.log('logger.init');
return logger.checkForLogFile().then(function(statObj) {
var exists = (typeof statObj === 'object');
console.log('exists', exists);
return logger;
});
};
Logger.prototype.log = function(msg) {
// requires that the log file exists and that we have a stream to it (create stream function removed)
console.log.call(null, '\033[36mLogging: ' + msg + ' \033[39m');
};
Logger.prototype.checkForLogFile = function() {
var logger = this;
return fs.statAsync(logger.filePath + logger.filename).then(function (statObj) {
console.log('statObj', statObj);
return statObj;
});
};
return Logger;
};

wait for modules are loaded

I have following code:
define([],
function() {
var AppSettings = function(){};
AppSettings.prototype = {
init: function() {
var that = this;
//...
require(views,function(){
var counter = 0;
for(view in that.settings.initViews) {
that.initViews[view] = new arguments[counter++];
}
console.log("init");
});
},
run: function() {
console.log("run");
}
};
return AppSettings;
}
);
And when I load AppSettings module:
require(["app_settings"],
function(AppSettings) {
var settings = new AppSettings();
settings.init();
setting.run();
}
);
I get following output:
run
init
This is probably because I am loding modules async in init method - but how I can 'wait' for them to load? I mean how I can ensure that all async alls are done and then call run?

Resources