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’) );