






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
You can easily learn node js from this cheatsheet. You can also refer it for revision of concepts.
Typology: Cheat Sheet
1 / 12
This page cannot be seen from the preview
Don't miss anything!
TABLE OF CONTENTS Running Node.js Node.js Global Object Node.js Module System The require Function Built-in Modules Creating Modules ECMAScript Modules Node.js Packages NPM Commands package.json node_modules package-lock.json Node.js Event Emitter Backend Concepts Express.js GET Routes POST Routes Routers Node.js Folder Structure Cross Origin Resource Sharing PM2 Commands Useful Links
// In src/fileModule.js function read(filename) { } function write(filename, data) { } module.exports = { read, write, }; // In src/sayHello.js const fs = require('fs'); fs.readFileSync('hello.txt'); // OR... const { readFileSync } = require('fs'); readFileSync('hello.txt');
Some modules like fs are built in to Node. These modules contain Node-specific features. Key built-in modules include: fs - read and write files on your file system path - combine paths regardless of which OS you're using process - information about the currently running process, e.g. process.argv for arguments passed in or process.env for environment variables http - make requests and create HTTP servers https - work with secure HTTP servers using SSL/TLS events - work with the EventEmitter crypto - cryptography tools like encryption and hashing We can create our own modules by exporting a function from a file and importing it in another module.
/ / I n s r c / f i l e M o d u l e. m j s f u n c t i o n r e a d ( f i l e n a m e ) { } f u n c t i o n w r i t e ( f i l e n a m e , d a t a ) { } e x p o r t { r e a d , w r i t e , } ; / / I n s r c / s a y H e l l o. m j s i m p o r t { w r i t e } f r o m '. / r e s p o n s e. m j s ' ; w r i t e ( ' h e l l o. t x t ' , ' H e l l o w o r l d! ' ) ; c o n s t { w r i t e } = r e q u i r e ( '. / f i l e M o d u l e. j s ' ) w r i t e ( ' h e l l o. t x t ' , ' H e l l o w o r l d! ' ) ; / / I n s r c / f i l e M o d u l e. j s e x p o r t s. r e a d = f u n c t i o n r e a d ( f i l e n a m e ) { } e x p o r t s. w r i t e = f u n c t i o n w r i t e ( f i l e n a m e , d a t a ) { } Some Node modules may instead use the shorthand syntax to export functions. We tell Node to treat JavaScript code as an ECMAScript module by using the .mjs file extension. Pick one approach and use it consistently throughout your Node project. Node developers often publicly share packages , that other developers can use to help solve common problems. A package is a collection of Node modules along with a package.json file describing the package. To work with Node packages we use NPM. NPM includes two things:
Node.js Packages
Node.js provides a built-in module to work with events.
For example, we can listen for the exit event on the current running process. In this case, the event has a code associated with it to be more specific about how the process is exiting. Client-server architecture Your frontend is usually the client. Your backend is usually the server. In a client-server architecture, clients get access to data (or "resources") from the server. The client can then display and interact with this data. The client and server communicate with each other using the HTTP protocol. API Short for Application Programming Interface. This is the set of functions or operations that your backend server supports. The frontend interacts with the backend by using only these operations. On the web, backend APIs are commonly defined by a list of URLs, corresponding HTTP methods, and any queries and parameters. CRUD Short for Create Read Update and Delete. These are the basic operations that every API supports on collections of data. Your API will usually save (or "persist") these collections of data in a database. RESTful RESTful APIs are those that follow certain constraints. These include: Client-server architecture. Clients get access to resources from the server using the HTTP protocol. const process = require('process'); process.on('exit', (code) => { console.log(About to exit with code: ${code}
); }); Backend Concepts
// In src/cards.router.js const cardsRouter = express.Router(); cardsRouter.get("/", (req, res) => { return res.json(cards); }); cardsRouter.get("/:cardId", (req, res) => { const cardId = req.params.cardId; return res.json(cards[cardId]); }); // In src/api.js const cardsRouter = require('./cards.router'); const api = express.Router(); api.use('/cards', cardsRouter); if (!card.value || !card.suit) { return res.status(400).json({ error: 'Missing required card property', }); } // Update your collection cards.push(card); // Send saved object in the response to verify return res.json(card); });
Node.js Folder Structure One typical folder structure for an API following RESTful architecture and using the Express framework can be found below. Node servers typically follow the Model View Controller pattern. Models live together in one folder. Controllers are grouped together based on which feature or collection they are related to. Views are typically managed by the front end, although some Node servers may serve static HTML or use templating engines like Handlebars.
node-project/ # top level project node_modules/ # all installed node packages data/ # static data files, if needed database.json src/ # the source code for your server models/ # models following the model-view-controller pattern comment.model.js post.model.js routes/ # one folder for each collection in your API feeds/ # folder for the user feeds collection feed.router.js # router listing all possible routes for user feeds feed.controller.js # controller with the implementation for each route posts/ post.router.js post.controller.js api.js # top level router connecting all the above routes services/ # any long running services or utilities mongo.js # e.g. connecting to a MongoDB database app.js # all Express middleware and routers server.js # the top level Node HTTP server .gitignore package-lock.json package.json This is just a reference. In the real world, every project will have differences in the requirements and the ideal project structure. Something all web developers soon come across is Cross Origin Resource Sharing (CORS). Browsers follow the Same Origin Policy (SOP) , which prevents requests being made across different origins. This is designed to stop malicious servers from stealing information that doesn't belong to them. Cross Origin Resource Sharing (CORS) allows us to allow or whitelist other origins that we trust, so that we can make requests to servers that don't belong to us. For example, with CORS set up properly, https://www.mydomain.com could make a POST request to https://www.yourdomain.com In Express we commonly set up CORS using the following middleware package: https://www.npmjs.com/package/cors Cross Origin Resource Sharing