Thursday, September 30, 2021

NodeJS 34: Send email from NodeJS using nodemailer

 NodeJS 34: Send email from NodeJS using nodemailer


Reference blog - https://www.w3schools.com/nodejs/nodejs_email.asp






Sendmail.js

"use strict";
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
//let testAccount = await nodemailer.createTestAccount();

//If we get this error - 535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8
//then we
//Need to turn on Less secure apps from this link - https://myaccount.google.com/lesssecureapps
console.log("Entered main method.............");
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: "pavan.******@gmail.com", // generated ethereal user
pass: "********", // generated ethereal password
},
});
console.log("Transporter object is ready.........");
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Test Mail" <foo@example.com>', // sender address
to: "pavankumar******@gmail.com", // list of receivers
subject: "Mail from NodeJS app ✔", // Subject line
text: "Mail from NodeJS app...?", // plain text body
html: "<b>Hello...</b>", // html body
});

console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);







Monday, March 2, 2020

NodeJS 33: MongoDB connect using Mongoose

NodeJS 33: MongoDB connect using Mongoose


https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications

https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

In Terminal:
npm install mongoose --save

items.js (Create Model)


// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var itemSchema = new Schema({
item: String,
available: Boolean,
soldQty: Number
});

// the schema is useless so far
// we need to create a model using it
var Item = mongoose.model('Item', itemSchema);

// make this available to our users in our Node applications
module.exports = Item;

IPLService.js (Save Model to MonogoDB)


var express = require('express');
var Item = require('./item');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

app.post('/BuildFlows',function(req,resp){
resp.writeHead(200,{'Content-Type':'application/json','Access-Control-Allow-Origin' : '*','Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'});
console.log('Inside post - BuildFlows');
console.log(req.body);

var item1 = new Item(req.body);
console.log("item1 : "+item1);
item1.save(function(err) {
if (err) throw err;
console.log('Item saved successfully...........');
});

resp.setHeader('Content-Type', 'application/json');
resp.end(JSON.stringify(req.body, null, 3));

});

















Sunday, September 16, 2018

NodeJS 32: SocketIO -> ChatApp

NodeJS 32: SocketIO -> ChatApp






#######################################CODE##################################



#################################
index.html
#################################
<html>
<head>

<title>Chat App</title>
<!-- bootstrap cdn -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- jquery cdn -->
<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

  <!-- client side socket io -->
  <script src="/socket.io/socket.io.js"></script>

  <style>
    body{
        margin-top:30px;
    }
 </style>
</head>
<body>
    <div class="container">
            <div class="row">
                <div class="col-md-4">
                       <div class="well">
                           <h3>Online users</h3>
                           <ul class="list-group" id="users"></ul>
                       </div>
                </div>
                <div class="col-md-8">
                        <div class="chat" id="chat"></div>
                        <form id="messageForm">
                            <div class="form-group">
                                <label>Enter Message</label>
                                <textarea class="form-control" id="message"></textarea>
                                <br/>
                                <input type="submit" class="btn btn-primary" value="Send Message"/>
                            </div>
                        </form>
                </div>
            </div>
        </div>

        <script>
        $(function(){
               var socket=io.connect();//new connection to server
               var $messageForm=$('#messageForm');
               var $message=$('#message');
               var $chat=$('#chat');
               $messageForm.submit(function(e){//event handler for submit button click
                   e.preventDefault(); //disable default click event
                   socket.emit('send message',$message.val());//trigger 'send message' event
                    $message.val('');     
                   console.log('submitted');
               });

                //listen for new message from server
                socket.on('new message',function(data){
                  $chat.append('<div class="well">'+data.msg+'</div>');
               });

           });
        </script>
</body>

</html>


#################################
server.js
#################################
var express=require('express');
var app=express();
var server=require('http').createServer(app);
var io=require('socket.io').listen(server);

users=[];
connections=[];

server.listen(3000);
console.log('server listening on 3000');

app.get('/',function(req,resp){
resp.sendFile(__dirname+'/index.html');
});

io.sockets.on('connection',function(socket){//when user connects to the chat server
    connections.push(socket);
    console.log('Connected : %s socket connection',connections.length);
    socket.on('disconnect',function(){//when user disconnects from the chat server
        connections.splice(connections.indexOf(socket),1);
        console.log('Disconnected : %s socket connection',connections.length);
    }) ;

    //once user click on send -> this will trigger
    socket.on('send message',function(data){
        console.log(data);
        io.sockets.emit('new message',{msg:data});//then server emits this message to broadcast to all users
 });

});


#################################
package.json
#################################
{
  "name": "mychatapp",
  "version": "1.0.0",
  "description": "mychatapp",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "socket.io": "^2.1.1"
  }
}





#################################CODE END#################################






NodeJS 31: UnitTesting with NodeJS - Mocha & Chai

NodeJS 31: UnitTesting with NodeJS - Mocha & Chai





########################################CODE##############################


###############################
test.js
###############################
var chai=require('chai');
var expect=chai.expect;

chai.should(); //activate assertion framework on mocha engine

function returnName(name){
return name;
}

function addNumbers(num){
return num+num;
}
function IsEven(inputVal){
return (inputval % 2)===0;
}


describe('Math Operation',function(){
    it('Returns a value added to itself',function(){
      addNumbers(5).should.equal(10);
  });
  it('Should return true for even number',function(){
    IsEven(4).should.equal(true);
    });
});

//test case
describe('1st unit test',function(){
  it('Returns the name passed',function(){
returnName('Amit').should.equal('Amit');
    });
});



###############################
app.js
###############################
module.exports=function(){
return 'hello';
}

###############################
appTest.js
###############################
const assert=require('chai').assert;
const app=require("../app");

describe('App',function(){
it('app should return hello..',function(){
assert.equal(app(),'hello');
    });
   
    it('app should return string..',function(){
assert.typeOf(app(),'string');
});

});




###############################CODE END ###############################

NodeJS 30: BuildTook with NodeJS - Using GULP

NodeJS 30: BuildTook with NodeJS - Using GULP


#################################CODE########################################



#############################
gulpfile.js
#############################
var gulp=require('gulp');

var uglify=require('gulp-uglify');


gulp.task('scripts',function(){
gulp.src('src/*.js').pipe(uglify()).pipe(gulp.dest('dist'));
});


#############################
package.json
#############################
{
  "name": "automation",
  "version": "1.0.0",
  "description": "automation",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC",
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-uglify": "^3.0.1"
  }
}




#############################
first.js
#############################
function myFirstFunction(){
return "first";
}


#############################
second.js
#############################
function mySecondFunction(){
return "second";
}



#############################CODE END#############################

NodeJS 29: BuildTook with NodeJS - Using GRUNT

NodeJS 29: BuildTook with NodeJS - Using GRUNT



#######################################CODE################################



######################
Gruntfile.js
######################
module.exports=function(grunt){
//trying to merge multiple js and send it to client as one file
//when we run the command it does automatically
grunt.initConfig({
concat :{  //to concatinate all js files in to 1 file
js: {
src: ['js/1.js', 'js/2.js'],
dest: 'build/js/scripts.js',
},
css: {
src: ['css/1.css', 'css/2.css'],
dest: 'build/css/styles.css',
}
},
watch:{  //to watch for file changes and execute
js:{
files: ['js/**/*.js'],
tasks: ['concat:js'], //to call only contact : js
},
css:{
files: ['css/**/*.css'],
tasks: ['concat:css'], //to call only contact : css
}
}
 });

//load this module
grunt.loadNpmTasks('grunt-contrib-concat');
//load this module
grunt.loadNpmTasks('grunt-contrib-watch');

//to automatically execute add it in 'default' section..
//CMD : grunt
 grunt.registerTask('default',['concat','watch']);

}


######################
package.json
######################
{
  "name": "grunt1",
  "version": "1.0.0",
  "description": "grunt",
  "main": "1.js",
  "dependencies": {
    "grunt": "^1.0.3",
    "grunt-cli": "^1.3.1",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-watch": "^1.1.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC"
}






######################CODE END ############################################

NodeJS 28: BuildTook with NodeJS (GRUNT & GULP)

NodeJS 28: BuildTook with NodeJS (GRUNT & GULP)