You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Node.js uses the V8 JavaScript enginge, enriched by extra APIs (e.g. to access local files on filesystem) and minus some browser-specific APIs (e.g. DOM API)
to run js file with node, use your installed Node.js environment and execute node app.js
Node.js works with utility modules that you can import and use
instead of import (ES6 modules), you use const fs = require('fs') (CommonJS modules)
Working with HTTP Requests
create a basic web server that runs locally
consthttp=require('http');// [1] send data from server to clientconstserver=http.createServer((request,response)=>{response.setHeader('Content-Type','text/html');// 'text/plain' would display exact stringresponse.write('<h1>Hello</h1>');response.end();})// [2] receive data from client to serverconstserver=http.createServer((request,response)=>{letbody=[];console.log(request.method,request.url);// set listener a) to send data event and b) send data finished eventrequest.on('data',(chunk)=>{body.push(chunk);});request.on('end',()=>{// rebuild sended data based on concatenated chunksbody=Buffer.concat(body).toString();constuserName=body.split('=')[1];response.setHeader('Content-Type','text/html');// use default browser POST behaviorresponse.write(` <h1>Hello ${userName||'Unknown User'}</h1> <form method="POST" action="/"> <input name="username" type="text"> <button type="submit">Send</button> </form> `);response.end();});});constPORT=3001;// listen() starts an ongoing server that can be accessed in browser with localhost:3000server.listen(process.env.PORT||PORT);// process.env.PORT will be set automatically by Heroku when you deploy your app
Framework and Tools
example project uses:
Express.js is a framework to simplify working with Node.js
body-parser: npm package to parse the body of HTTP requests
ejs: npm package for embedded JavaScript templating for server-side rendered HTML