const debug = require('debug')('nameOfDebugVar');
console.log("Var Val through the debugger");
let myArray= [].fill(120,0,10000);
let secondArr = myArray.map(elem => item*5);
debug("POST LOOP");DEBUG=nameOfDebugVar node nameOfFile.js- SOAP
- REST
βββ /models
βββ server.js
βββ node_modules
βββ package-lock.json
βββ package.json
- HTTP(built-in): Allow NodeJS to transfer data over the HTTP Protocol to use it use the require keyword
require('http');- Express: Node.js web application framework tool that helps with development of web and mobile applications
require('express');- MySQL: NodeJS Driver to work and connect with the relational database MySQL
require('mysql');- Dot-env: NodeJS Driver which enables you to load environment variables from a file
require('dotenv');- Nodemon: A Live server for your NodeJS application. Restarts automatically when any changes take place placed in your package.json file
npm install -g nodemon- Debug: A JS Debugging utility for your NodeJS application
npm install debug- Passport: An authentication middleware for you NodeJS application
npm install passportapp.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' })
);- Bcrypt: Library used to Hash Password in Your Application
npm install bcrypt- Mongoose: MongoDB Object Modeling Package which allows MongoDB to work with NodeJS
npm install mongoose//In NodeJS
const mongoose = require('mongoose');
//ES6 Notation
import mongoose from 'mongoose';- A DB Model Using Mongoose library thanks to its Schema Interace
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FirstPost = new Schema({
author: ObjectID,
lovesDJ: Boolean,
dateHeWatchedBD: Date,
thingsHeLoves: Array,
favSaying: String
});- I can also use Input Validation before saving the data into my DB
const Comment = new Schema({
name: { type: String, default: 'hahaha' },
age: { type: Number, min: 18, index: true },
bio: { type: String, match: /[a-z]/ },
date: { type: Date, default: Date.now },
buff: Buffer
});
// a setter
Comment.path('name').set(function (v) {
return capitalize(v);
});
// middleware
Comment.pre('save', function (next) {
notify(this.get('email'));
next();
});- Register First At MongoDB and Select A Plan
- Create Your Cluster
- Add A User
- Select one of the two scenarios:
a. Whitelist Any IP(ONLY FOR LEARNING PURPOSES)
b. Whitelist your IP
- To Connect Your Application...Click on Connect Application
- Select NodeJS as Your Driver
- Add the connection string into your application code in the db.json file
- Store your username and password in a .env file inside an environment variable and do not commit this file
- To be safe add .env file to your .gitignore file so that Git Doesn't track it
- Usage:
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
//how to hash a password
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});root
βββfrontend
βββββββ node_modules
βββββββ package.json
βββββββ package-lock.json
βββββββ .gitignore
βββββββ debug.log
βββββββ public
βββββββ favicon.ico
βββββββ index.html
βββββββ manifest.json
βββββββ src
βββββββββββββ App.css
βββββββββββββ App.js
βββββββββββββ App.test.js
βββββββββββββ components
βββ index.css
βββ index.js
βββ logo.svg
βββ serviceWorker.js
βββbackend
βββ /controllers
βββ server.js
βββ /models
βββ /routes
βββ server.js
βββ node_modules
βββ package-lock.json
βββ package.json
root
βββ /frontend
βββββββ /node_modules
βββββββ package.json
βββββββ package-lock.json
βββββββ .gitignore
βββββββ debug.log
βββββββ /public
βββββββ favicon.ico
βββββββ index.html
βββββββ manifest.json
βββββββ /src
βββββββββββββ App.css
βββββββββββββ App.js
βββββββββββββ App.test.js
βββββββββββββ components
βββ index.css
βββ index.js
βββ logo.svg
βββ serviceWorker.js
βββ /backend
βββ /controllers
βββ server.js
βββ /models
βββ /routes
βββ server.js
βββ /node_modules
βββ package-lock.json
βββ package.json
βββ /model
βββ /schema
|ββ 375fanb.sql
βββ 429fanb.sql
root
βββnodejs
βββ src
βββ app.js --------------------- Application Entry Point
βββ /api-routes ---------------- Controller Layer: For API Routes
βββ /config -------------------- where you store your environment vars
βββ /loaders ------------------- loaders for startup modules
βββ /models -------------------- Data Access Layer: Database models
βββ /scripts ------------------ NPM scripts
βββ /services ------------------ Service Layer: Store Your business logic
βββ /subsribers ---------------- asynchronous Event Handlers
βββ /test ---------------------- For Unit Testing
βββ package-lock.json
βββ package.json
npm i -D nodemonnpx nodemon yourfilename.jsnpm i -D concurrentlyconst http = require('http'),
//this is a callback function
makeServer = function (request,response){
//must you want http displayed I must include the http header with suitable content type
response.writeHead(200,{'Content-Type':'text/plain'});
response.write('Hello world');
response.end();
},
server = http.createServer(makeServer);
server.listen(3000,()=>{
console.log('Node server created at port 3000');
});const http = require('http'),
url = require('url'),
makeServer = function (request,response){
let path = url.parse(request.url).pathname;
console.log(path);
if(path === '/'){
response.writeHead(200,{'Content-Type':'text/plain'});
response.write('Home Page');
}
else if(path === '/about'){
response.writeHead(200,{'Content-Type':'text/plain'});
response.write('About page');
}
else if(path === '/ftn'){
response.writeHead(200,{'Content-Type':'text/plain'});
response.write('429 page');
}
else{
response.writeHead(404,{'Content-Type':'text/plain'});
response.write('Error page');
}
response.end();
},
server = http.createServer(makeServer);
server.listen(3000,()=>{
console.log('Node server created at port 3000');
});- An API Endpoint is a function within your API that returns Data
- A RESTful API is an API whereby the server nor the client have no idea of the state(object) of one another
- By using this interface, different clients hit the same REST Endpoints, perform the same actions, and receive the same responses without minding the state of one another
- create a folder
mkdir nodejs_api1a. navigate to the folder
cd nodejs_api- Run the command npm init to create our package.json file
npm init- Install My Middleware
npm install express --save- 3 necessary files for my app
touch server.js index.html users.js- Goto Your Users.js File
// I use module.exports so that every program in my app can use it
module.exports.users = [
{
name: 'Mark Ramiro',
age : 19,
occupation: 'Aerospace Engineer',
graduated : false,
classes : ['Calc3','EPII','ChemII']
},
{
name: '55732',
age : 24,
occupation: 'Developer',
graduated : true,
classes : ['429','375','373']
},
{
name: 'Mike',
age : 34,
occupation: 'Full Stack Developer',
graduated : true,
classes : ['CALC3','EPII','OChemII']
},
]- I use express to create my server
const express = require('express'),
server = express(),
users = require('./users');
//setting the port.
server.set('port', process.env.PORT || 3000);
//Adding routes
server.get('/',(request,response)=>{
/*
this searches for the file and sends it to the browser
dirname is my root folder where my server is running from
*/
response.sendFile(__dirname + '/index.html');
});
//I use response.json to websites requesting the data in JSON format
server.get('/users',(request,response)=>{
response.json(users);
});
//Binding to localhost://3000
server.listen(3000,()=>{
console.log('Express server started at port 3000');
});- Create the index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Home page</title>
</head>
<body>
<button>Get data</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
const btn = document.querySelector('button');
btn.addEventListener('click',getData);
function getData(e){
$.ajax({
url : '/users',
method : 'GET',
success : function(data){
console.log(data);
},
error: function(err){
console.log('Failed');
}
});
}
</script>
</body>
</html>- In the root folder I run the below command to start my nodejs application
node server.js- You just created a NodeJS Crud App
- The File System allows you to work with files on your local computer
- To Use it here is how we import it
var fs = require('fs');var url = require('url');
- Every action you take on your computer is an action
- I can fire an event in NodeJS whenever a file gets opened or closed
var fs = require('fs');
var myfile = fs.createReadStream('./polaanfb.txt');
myfile.on('open', function () {
console.log('The polanfb text file is open');
});- I can also use the built-in events module that NodeJS provides me with
var events = require('events');
var eventEmitter = new events.EventEmitter();//how to instantiate an event emmitter object
var theEventHandler = function () {
console.log('2526: I Contacted 7652626 to get an A in 1336 and contacted 35 to get an A in 429');
}
eventEmmitter.on('Something happened please fire this event.', theEventHandler);//Assigning eventEmitter to theEventHandler
//firing the event
//How to emit the event
eventEmitter.emit('Emitted!');var http = require('http');
var formidable = require('formidable');
var fs = require('fs');var nodemailer = require('nodemailer');