Pages

(Node) Consume a soap service

var soap = require('soap');
var parseString = require('xml2js').parseString;
var url = 'xxx.wsdl';

var args = { _xml: "xml representation of the request"  };
soap.createClient(url, function(err, client) {
if(err)
console.log("error:"+err);

client.funName(args, function(err, result, rawResponse, soapHeader, rawRequest) {
if(err)
console.log(err);

//optional, if response needed in json format
parseString(rawResponse, function (err, jsonResult) {
res.contentType('application/json');
res.send(JSON.stringify(jsonResult, null, 4));
});
});
});

(Node) Read from xlsx file

//npm install xlsx

if(typeof require !== 'undefined') XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
        // Selects the worksheet
var worksheet = workbook.Sheets["Sheet1"];
var range = XLSX.utils.decode_range(worksheet['!ref']);

for(var R = range.s.r; R <= range.e.r; ++R) {
  for(var C = range.s.c; C <= range.e.c; ++C) {
    var cell_address = {c:C, r:R};
    /* if an A1-style address is needed, encode the address */
    var cell_ref = XLSX.utils.encode_cell(cell_address);
            if(worksheet[cell_ref])
console.log(worksheet[cell_ref].v);
  }
}

Reference: https://www.npmjs.com/package/xlsx

(Node) Send Mail


// Following code send mail using SMTP information

Prerequisite NPM commands:
npm init -y
npm install nodemailer --save

Code starts from here

const nodemailer = require('nodemailer');

exports.sendMail = function(req, res, next) {
 nodemailer.createTestAccount((err, account) => {
      // create reusable transporter object using the default SMTP transport
      let transporter = nodemailer.createTransport({
          host: <<SMTP_IP>>,
          port: <<SMPT_PORT>>,
          secure: false,
          tls: {
          // do not fail on invalid certs
          rejectUnauthorized: false
      }

      });

      // setup email data with unicode symbols
      let mailOptions = {
          from: '"Harish Dewangan" <DoNotReply@company.com>', // sender address
          to: 'harish.dewangan@company.com', // list of receivers
          subject: 'Test mail , // Subject line
          html:    '<h2>This is a test mail <h2>'
      };

      // send mail with defined transport object
      transporter.sendMail(mailOptions, (error, info) => {
          if (error) {
              return console.log(error);
          }
          console.log('Message sent: %s', info.messageId);
      });

  });

 }

(Node) Web Scraping

// Following code gets celeb names from IMDB who born on current date, search their brief information in wiki and finally print in a form of table.

Prerequisite NPM commands:
npm init -y
npm install request --save
npm install request-promise --save
npm install cheerio--save
npm install cli-table--save


Code starts from here

const rp = require('request-promise');
const cheerio = require('cheerio');
const Table = require('cli-table');

let table = new Table({
head: ['userName', ' userInfo'],
colWidths: [15, 200,]
})

const options = {
url: `http://www.imdb.com/`,
json: true,
transform: body => cheerio.load(body)
}

rp(options)
.then(function ($) {
let userData = [];

// Get the div which has class 'widget_caption caption_below'  residing under div with class 'ab_borntoday'
var bornToday = $('div.ab_borntoday').find('.widget_caption.caption_below');
var name;
if(bornToday.length>0){
bornToday.each(function(i, elem) {
name = $(this).text().trim().replace(' ','_').split('(')[0];
console.log("Name:"+name)
userData.push({name:name});
});
}
getUserDetails(userData);
})
.catch((err) => {
console.log(err);
});


function getUserDetails(userData) {
var i = 0;
function next() {
if (i < userData.length) {
var options = {
url: `https://en.wikipedia.org/wiki/` + userData[i].name,
transform: body => cheerio.load(body)

}
rp(options)
.then(function ($) {
process.stdout.write(`.`);

var userInfo = $('div.mw-parser-output').find('p').text().substring(0,150);
table.push([userData[i].name, userInfo]);
++i;
return next();
})
}else {
printData();
}
}
return next();
};

function printData() {
console.log("✅");
console.log(table.toString());
}