Friday, 29 December 2017

link for encryption example

https://gist.github.com/raytung/f7dc78bb4310d02217111246da8cfdb3




/*
 * AWS Sdk KMS spike: (assuming node v6.6+)
 * 1 - Create master key at KMS
 * 2 - Copy alias or ARN
 * 3 - run this i.e.
 * $ node spike.js KEY_ALIAS YOUR_PLAINTEXT_TO_ENCRYPT
 */
const AWS = require('aws-sdk');

// aws-sdk is not reading my region info so i'll have to set it here
// maybe you have it working properly
// aws-sdk reads in your aws credentials from ~/.aws/credentials
AWS.config.update({ region:'ap-southeast-2' });

const kms = new AWS.KMS();

// your input args
const KeyId = process.argv[2];
const Plaintext = process.argv[3];

// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/KMS.html#encrypt-property
// @params KeyId String
// @params Plaintext String | Buffer
// @params EncryptionContext object (optional) http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html
// @params GrantTokens [Strings] (optional) http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant
const params = {
 KeyId: keyId, // your key alias or full ARN key
 Plaintext: secret, // your super secret.
};

kms.encrypt(params).promise().then(data => {
 const base64EncryptedString = data.CiphertextBlob.toString('base64');
 console.log('base64 encrypted string: ' + base64EncryptedString);
 return base64EncryptedString;
})
.then(base64EncryptedString => {
 // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/KMS.html#decrypt-property
 // @params KeyId String
 // @params CiphertextBlob Buffer(base64)
 // @params EncryptionContext object (optional) http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html
 // @params GrantTokens [Strings] (optional) http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant
 return kms.decrypt({
  CiphertextBlob: Buffer(base64EncryptedString, 'base64')
 }).promise();
})
.then(data => {
 console.log('Your super secret is: ' + data.Plaintext.toString('ascii'));
 // do something with it
})
.catch(err => console.log(err, err.stack));

Thursday, 21 December 2017

lodash orderby example

var questions = [
    { number: '1', text: 'question_1','rank':5,company:"lives"},
    { number: '2', text: 'question_2','rank':4,company:"acme"},
    { number: '3', text: 'question_3','rank':6,company:"sparky"},
];


questions=_.orderBy(questions, ['company'],['asc']);
 obj = {print: questions};

cloud search suggest example.


http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html#configuring-suggesters

-----------------------------------------------------------------------------
http://search-imdb-hd6ebyouhw2lczkueyuqksnuzu.us-west-2.cloudsearch.amazonaws.com/2013-01-01/suggest -d"q=oce&suggester=suggest_title" {"status":{"rid":"646f5s0oDAr8pVk=","time-ms":2}, "suggest":{ "query":"oce", "found":3, "suggestions":[ {"suggestion":"Ocean's Eleven","score":0,"id":"tt0054135"}, {"suggestion":"Ocean's Thirteen","score":0,"id":"tt0496806"}, {"suggestion":"Ocean's Twelve","score":0,"id":"tt0349903"} ] } }






-----------------------------------------------------------------------------------

Submitting Suggest Requests in Amazon CloudSearch

You submit suggest requests via HTTP GET to your domain's search endpoint at 2013-01-01/suggest. For information about controlling access to the suggest service, see configure access policies.
You must specify the API version in all suggest requests and that version must match the API version specified when the domain was created.
For example, the following request gets suggestions from the search-movies-rr2f34ofg56xneuemujamut52i.us-east-1.cloudsearch.amazonaws.com domain for the query string oce using the suggester called title.
---------------------------------------------------------------------------------
let suggest={"status":{"rid":"646f5s0oDAr8pVk=","time-ms":2},
 "suggest":{
   "query":"oce",
   "found":3,
   "suggestions":[
     {"suggestion":"Ocean's Eleven","score":0,"id":"tt0054135"},
     {"suggestion":"Ocean's Thirteen","score":0,"id":"tt0496806"},
     {"suggestion":"Ocean's Twelve","score":0,"id":"tt0349903"}
   ]
 }
}
undefined
suggest
{status: {…}, suggest: {…}}status: {rid: "646f5s0oDAr8pVk=", time-ms: 2}suggest: {query: "oce", found: 3, suggestions: Array(3)}__proto__: Object
suggest.suggest.suggestions
(3) [{…}, {…}, {…}]0: {suggestion: "Ocean's Eleven", score: 0, id: "tt0054135"}1: {suggestion: "Ocean's Thirteen", score: 0, id: "tt0496806"}2: {suggestion: "Ocean's Twelve", score: 0, id: "tt0349903"}length: 3__proto__: Array(0)
suggest.suggest.suggestions[0]
{suggestion: "Ocean's Eleven", score: 0, id: "tt0054135"}
suggest.suggest.suggestions[0].suggestion
"Ocean's Eleven"

Friday, 15 December 2017

base 64 encryption

https://stackoverflow.com/questions/6182315/how-to-do-base64-encoding-in-node-js


> console.log(new Buffer("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(new Buffer("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World
https://stackoverflow.com/questions/14573001/nodejs-how-to-decode-base64-encoded-string-back-to-binary
down voteaccepted
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer and pass 'base64' as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from exists :
if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions
    buf = new Buffer(b64string, 'base64'); // Ta-da
https://stackoverflow.com/questions/23097928/node-js-btoa-is-not-defined-error

166down voteaccepted
The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.
If you need to convert to Base64 you could do so using Buffer:
console.log(Buffer.from('Hello World!').toString('base64'));
Reverse (assuming the content you're decoding is a utf8 string):
console.log(Buffer.from(b64Encoded, 'base64').toString());

Friday, 8 December 2017

pomise tutorial


https://scotch.io/tutorials/javascript-promises-for-dummies
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261
/* ES5 */
var isMomHappy = true;

// Promise
var willIGetNewPhone = new Promise(
    function (resolve, reject) {
      let data=new Promise(function(resolve,reject){

        let i;
      for(i=0;i<100;i++)
      {
        console.log(i);
      }

    if(i==100)
    {
      resolve(isMomHappy);
    }
  }).then(function(isMomHappy){
        if (isMomHappy) {
            var phone = {
                brand: 'Samsung',
                color: 'black'
            };
            resolve(phone); // fulfilled
            //console.log(phone);
        } else {
            var reason =new Error('mom is not happy');
            reject(reason); // reject
        }
      }).catch(function(e){

        console.log(e);
      });

}).then(function(phone){
  console.log(phone);
}).
catch((reason)=>{
  console.log(reason);
});

append " " cotes

'"'+name+'"'

Thursday, 7 December 2017

node example two

var Promise = require("bluebird");
exports.getuser=function(myobj)
{

console.log("calll");
function data(myobj1,callback){
//setTimeout(function() {
Object.keys(myobj1).forEach(function(v){
//console.log("keys==="+v+"value=="+myobj[v]);
myobj1[v]="op";
//console.log(myobj);
setTimeout(function() {
console.log("pawan");
},100000);
});

//});
let data1=callback(myobj1);
return data1;
}
function example(data1){
console.log("mydata---"+JSON.stringify(data1))
return data1;
}
data(myobj,example);

};
exports.setuser=function()
{
return "kumar";
};

node example one

var Promise = require("bluebird");
var http=require("http");
var mydata=require('./exampledata');
var request=require("request");
let myobj={"id":"1","city":"pune","name":"pawan","rank":"5"};
var Promise = new Promise(function (resolve, reject) {
let d=mydata.getuser(myobj);
resolve(myobj);
}).then(function(data){
return data;
console.log("opooo--------------------"+JSON.stringify(data));
}).then(function(data){
console.log("then1"+JSON.stringify(data));
return data;
}).then(function(data){
console.log("then2"+JSON.stringify(data));
return data;
}).then(function(data){
console.log("then3"+JSON.stringify(data));
}).catch(error =>{
console.log(error);
});
//let m=mydata.getuser();
console.log("promise example");
let myarray=["pawan","kumar","yadaw","munna"];
/*myarray.map(function(fileName) {
    // Promise.map awaits for returned promises as well.
    //return fileName;
console.log(fileName);
});*/
/*myarray.map(function(i) {
console.log(i);
//return i;
}).then(function(results) {
console.log(results);
    // Now they're back as an array
});*/

Wednesday, 6 December 2017

var promise=require("promise");
var http=require("http");
var request=require("request");
var promise = new Promise(function (resolve, reject) {
  request.get('http://www.google.com', function (err, res) {
    if (err)
{
console.log("error-----------------");
reject(err);
}
    else
{
console.log("success");
resolve(res);
var data="pawan";

//console.log(res);
}
  });
}).then(function(data){
console.log("opooo--------------------"+JSON.stringify(data));
}).then(function(data){
console.log("then1");
}).then(function(){
console.log("then2");
}).then(function(){
console.log("then3");
})
.catch(error =>{
console.log(error);
});
console.log("promise example");

Tuesday, 5 December 2017

key and value

var a = {"cat":"large", "dog": "small", "bird": "tiny"};
Object.keys(a).map(function (k, v){
    console.log(k, '==',a[k]);
});

Thursday, 30 November 2017

how to debugg nodejs in chrome

https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27

Wednesday, 29 November 2017

dynamodb client side encryption in node js code

https://stackoverflow.com/questions/35213615/encrypting-values-using-amazon-kms-storing-retrieving-using-dynamodb-with-lam