nodejs Flashcards
Get started with Nodejs
Nodejs is modular and that is its power.
The NPM helps tap into that modularity.
What to write to define destination of current directory?
__dirname
Initialize nodejs
npm init
express.js - package of nodejs
npm install express
const express = require(‘express’);
const app = express( );
body-parser - package of nodejs
USED TO PARSE DATA AND RECEIVE THEM IN USABLE FORM
npm install body-parser
const bodyParser = require(‘body-parser’);
//if app is the const holding the value of express( )
app.use( bodyParser.urlencoded( {extended: true} ) );
START A SERVER
app.listen(port here, console command here);
Example –
app.listen( 8080, console.log(‘Server has started on port 8080’));
Route websites using Express.js
Respond to designated path
app.get( ‘/route here’ , function (req, res)
{
res.send(‘’)
});
OR
app.get( ‘/route here’ , function (req, res)
{
res.sendFile(__dirname + ‘html document here’);
});
POST result to the Submitted action
apt.post('/destination page', function (req, res) { var variable = parseFloat(req.body.nameOfSubmittedValue); // calculations --- res.send('HTML result to send'); } );
Access API with HTTPS module of nodejs
const https = require(‘https’);
https.get ('url here' , function (request, response) { console.log(response.statusCode); response.on( 'data' , function (data) { const someData = JSON.parse(data); console.log(someData) } );
The first parameter ‘data’ shouldnt be change for response.on( ) if we want to receive data.
JSON.parse && JSON.stringify
.parse unpacks the JSON file and structures in a more readable form.
.stringify packs the JSON and compresses it to reduce file size.
Encoding character of response.send
response.setHeader(“Content-Type”, “text/html ; charset=utf-8”);
POST response for the SUBMIT input
response.send(‘text/html here’) sends a text or html in response to submit input
For multi-line response -
response. write(‘text/html here’)
response. write(‘text/html here’)
response. send( )
Redirect website
When a post method is called –
app.post ( ‘some path here’, (req, res) => { res.redirect (‘redirect path here’); } )
Dynamic Port selection for Heroku
Documentation on heroku suggests we listen to following
app.listen ( process.env.PORT )
OR
app.listen ( process.env.PORT || 3000 )
[ This allows us to listen to the port dynamically according to heroku’s allotment and also listen to 3000 at all times]
Pointing to static files like CSS and Javascript
1) Make a public folder in the root.
2) Require express in your nodejs file.
3) app.use( express.static (‘public’) );
CSS for HTML through nodejs
You have to make a ‘public’ folder so expressjs can access ‘root’ of the project. For expressjs, ‘public’ is the root of the project, and not the actual root.
Oh, also tell express about this folder by —
app.use(express.static(“public”));
How does .post method work?
When HTML form passes an input, it has an action=”path1 here” property. This is the path, where it sends the input.
In the server, app.post(“path1 here”) will capture that input and then bodyparser maybe used to parse the input into usuable variable.
For EJS—–
To add to this - the button type=”submit” can have a name and value declared by name=”name here” and value=”value here” inside the opening tags of button.
Example -
(angl)button type=’button’ name=”hereName” value=”hereValue”(angl_clos) Text here (angl)/button(angl_clos)
so when this submit an input - bodyparser will intercept object with name of variable and its value + another property saying
“hereName: hereValue”
This can be used to do more specific operations like adding variables to different array depending on value of submit button which can be changed dynamically now thanks to ejs.
How do node modules work?
[exports.function]
We can ‘require’ a local javascript like we require modules like express and bodyparser that we install through npm.
These local javascript can be exported using a method called ‘module’.
Module helps to export an external function into another javascript.
So –> module.exports returns an object when called.
Hence we can have multiple functions tied to this date. Like —
module. exports.someFunction = function ( ) { //code here; }
module. exports.someFunction2 = function ( ) { //code here; }
and the specific function can now be executed externally after ‘requiring’ the javascript and calling myVar.someFunction( );
or calling myVar.someFunction2 ( );
Btw, ‘module.exports.function’ can be written as just ‘exports.function’ and it would mean the same thing.
Express Routing Parameters
Helps in quick routing setup without needing to write multiple app.get( ) parameters multiple times
app.get(‘ /:enter_new_path_here ‘, function(request, response) { // code here for template }
Lodash module
npm install lodash
var _ = require(‘lodash’);
API documentation : https://lodash.com/docs/4.17.15
This is a very handy module which can do a number of things. Among which is a feature that can turn any type of casing into lower case title with appropriate spacing.
For exmaple - we want to lowerCase a title smartly -
_.lowerCase('--Foo-Bar--'); // => o/p - 'foo bar'
_.lowerCase('fooBar'); // => 'foo bar'
_.lowerCase('\_\_FOO_BAR\_\_'); // => 'foo bar'