0% found this document useful (0 votes)
63 views

Assignment 1

The document discusses various Node.js libraries and concepts including: 1. Bcryptjs for encrypting passwords, Mongoose for database operations, and Axios for making HTTP requests to connect a client and server. 2. Express is used to build the server, handling GET and POST requests. 3. Dotenv is used to store configuration variables separate from code for security. 4. Additional libraries covered are Moment for date handling, Cloudinary for image management, and Chalk for terminal string styling. 5. Node-nlp enables natural language processing, and npm-login-register provides basic user authentication functionality.

Uploaded by

Pakmedic inc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Assignment 1

The document discusses various Node.js libraries and concepts including: 1. Bcryptjs for encrypting passwords, Mongoose for database operations, and Axios for making HTTP requests to connect a client and server. 2. Express is used to build the server, handling GET and POST requests. 3. Dotenv is used to store configuration variables separate from code for security. 4. Additional libraries covered are Moment for date handling, Cloudinary for image management, and Chalk for terminal string styling. 5. Node-nlp enables natural language processing, and npm-login-register provides basic user authentication functionality.

Uploaded by

Pakmedic inc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

TCS Assignment-1

Abdul Moeed

FA19-BCS-003

BCS-VI(A)

Sir Rashid Mukhtar
1- Bcryptjs: Information encryption library.

import bcrypt from 'bcryptjs';

let salt = bcrypt.genSaltSync(10);


let hash = bcrypt.hashSync("B4c0/\/", salt);

console.log(bcrypt.compareSync("B4c0/\/", hash));
console.log(bcrypt.compareSync("not_bacon", hash));

console.log(hash);
console.log(salt);

2- Mongoose: Database for CRUD operations on data.

import mongoose from 'mongoose';


mongoose.connect("mongodb://localhost:27017/comsats", err => {
if(err) console.log(err);
let studentSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
rollno: {
type: String,
required: true
}
});
let studentModel = mongoose.model('Student', studentSchema);
const student = new studentModel({
name: "HEHE",
rollno: "12344"
});
student.save((err, data) => {
if (err) throw err;
console.log(data);
})
});

Assignment-1 PAGE 2
3- Axios: Promise based HTTP client for the browser and node.js used at the client
side to connect with the server side and send http requests to the server.

import axios from 'axios';

async function makeGetRequest() {

let res = await axios.get('http://localhost:5000/');

let data = await res.data.message;

console.log(data);
}

const makePostReq = async () => {

const payLoad = {
name: "Abdul Moeed",
regno: "003"
};

const res = await axios.post('http://localhost:5000/newUser', payLoad);

const data = res.data;

console.log(data);

makePostReq();

makeGetRequest();

Assignment-1 PAGE 3
import express from 'express';
import cors from 'cors';

const app = express();


const port = process.env.PORT || 5000;

app.use(express.urlencoded({ extended: true }));


app.use(express.json());

app.use(cors());
app.listen(port, () => console.log("Backend server live on " + port));

app.get("/", (req, res) => {


res.send({ message: "We did it!" });
});

app.post("/newUser", (req, res) => {

const user = req.body;

console.log(user);

res.send(`${user.name}'s data recieved`);

})

Assignment-1 PAGE 4
4- Dotenv: Dotenv is a zero-dependency module that loads environment variables
from a .env file into process.env. Storing configuration in the environment
separate from code. This also allows you to protect your credentials such as
database connection strings, port numbers etc.

import express from 'express';


import cors from 'cors';
import dotenv from 'dotenv';

const result = dotenv.config()

if (result.error) {
throw result.error
}

console.log(result.parsed)

const app = express();


const port = process.env.PORT || 5000;

app.use(express.urlencoded({ extended: true }));


app.use(express.json());

app.use(cors());
app.listen(port, () => console.log("Backend server live on " + port));

app.get("/", (req, res) => {


res.send({ message: "We did it!" });
});

app.post("/newUser", (req, res) => {

const user = req.body;

console.log(user);

res.send(`${user.name}'s data recieved`);

})

Assignment-1 PAGE 5
5- Nodemailer: An api to send emails as easy as cake!

import nodemailer from '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();

// create reusable transporter object using the default SMTP transport


let transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
});

// send mail with defined transport object


let info = await transporter.sendMail({
from: '"ABDUL MOEED 👻" <[email protected]>', // sender address
to: "[email protected], [email protected]", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});

console.log("Message sent: %s", info.messageId);


// Message sent: <[email protected]>

// Preview only available when sending through an Ethereal account


console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

Assignment-1 PAGE 6
main().catch(console.error);

Assignment-1 PAGE 7
6- Moment: A lightweight JavaScript date library for parsing, validating,
manipulating, and formatting dates.

import moment from 'moment';

console.log(moment().format('LTS')); // 3:01:08 AM);


console.log(moment().format('LLLL')); // Friday, March 18, 2022 3:01 AM)

Assignment-1 PAGE 8
7- Cloudinary: The Cloudinary Node SDK allows you to quickly and easily
integrate your application with Cloudinary. Effortlessly optimize, transform,
upload and manage your cloud's assets.

// Import the configuration classes.


import {URLConfig} from "@cloudinary/url-gen";
import {CloudConfig} from "@cloudinary/url-gen";
import {CloudinaryImage} from '@cloudinary/url-gen';

// Set the Cloud configuration and URL configuration


const cloudConfig = new CloudConfig({cloudName: 'demo'});
const urlConfig = new URLConfig({secure: true});

// Instantiate a new image passing the Cloud and URL configurations


const myImage = new CloudinaryImage('docs/dogs', cloudConfig, urlConfig);

// This returns: https://res.cloudinary.com/demo/image/upload/docs/shoes


const myURL = myImage.toURL();

console.log(myURL);

Assignment-1 PAGE 9
Assignment-1 PAGE 10
8- Chalk: Terminal string styling library to make debugging easier for server side.

import chalk from 'chalk';

const log = console.log;

// Combine styled and normal strings


log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API


log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments


log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)


log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));

// ES2015 template literal


log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// Use RGB colors in terminal emulators that support it.


log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));

Assignment-1 PAGE 11
9- Node-nlp: A natural language processing library for node js to recognize human
speech.
10- import { NlpManager } from 'node-nlp';
11-
12- const manager = new NlpManager({ languages: ['en'], forceNER: true });
13- // Adds the utterances and intents for the NLP
14- manager.addDocument('en', 'goodbye for now', 'greetings.bye');
15- manager.addDocument('en', 'bye bye take care', 'greetings.bye');
16- manager.addDocument('en', 'okay see you later', 'greetings.bye');
17- manager.addDocument('en', 'bye for now', 'greetings.bye');
18- manager.addDocument('en', 'i must go', 'greetings.bye');
19- manager.addDocument('en', 'hello', 'greetings.hello');
20- manager.addDocument('en', 'hi', 'greetings.hello');
21- manager.addDocument('en', 'howdy', 'greetings.hello');
22-
23- // Train also the NLG
24- manager.addAnswer('en', 'greetings.bye', 'Till next time');
25- manager.addAnswer('en', 'greetings.bye', 'see you soon!');
26- manager.addAnswer('en', 'greetings.hello', 'Hey there!');
27- manager.addAnswer('en', 'greetings.hello', 'Greetings!');
28-
29- // Train and save the model.
30- (async() => {
31- await manager.train();
32- manager.save();
33- const response = await manager.process('en', 'I should go now');
34- console.log(response);
35- })();

Assignment-1 PAGE 12
Assignment-1 PAGE 13
10- npm-login-register: A library to implement basic and simplistic login and
registration functionality in your application. This library can also be used for testing
frontend before connecting it to the backend.

import LoginRegister from 'npm-login-register';

let dbName = "db";


let userTable = "table";
let dbType = "mongodb";
let loginReg = new LoginRegister(dbName, userTable, dbType);

const data = {
email: "[email protected]",
name: "hehe",
password: 694200
};

const email = "[email protected]";

loginReg.userRegister(data, (res) => {


console.log(res);
});

loginReg.userLogin(data.email, data.password, (res) => {


console.log(res);
});

loginReg.userLogin(email, data.password, (res) => {


console.log(res);
});

Assignment-1 PAGE 14
Assignment-1 PAGE 15

You might also like