Coding Notes

Node.js

By Rae

Notes

  • Node.js allows developers to build fast and scalable applications using a single language, JavaScript.
  • Where Node.Js is Found
    • Server-rendered apps
    • Microservices
    • Backend services for mobile
    • Bots and scrapers
    • Desktop Apps
    • Automation tools
    • Internet of Things devices
  • Node.js is NOT a language, it's an environment in which you can write JavaScript.
  • The core HTTP model
    • creating a server
    • sending status codes (200, 400, etc.)
    • sending readers
    • handling requests/responses
    • filtering data
    • extracting query params
  • Package.json
    • Package.json is the blueprint
    • It contains metadata (name, version, author, description, etc.)
    • Simplifies collaboration (manages dependencies, defines start script)
    • Using npm init in the terminal will include creating a Package.json file for you. It will ask for the name, version, description, entry point, test command, git repository, keywords, author, and license.
    • After creating the package.json it will look something like { "name": "entered-name", "version": "1.0.0", "description": "entered description", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js" }, "author": "entered author name", "license": "ISC" }
    • After creating the package.json file you can start your project by writing npm start in the terminal instead of node server.js.
  • With node.js you can write javaScript into the terminal.
  • The HTTP Module
    • In server.js put import http from 'node:http'. You could write just import http from 'http', but it is best practice to include node as it tells the app that it is a node module not a javaScript module. This can speed up performance.
    • In the package.json file add "type": "module", to the object below "main".
    • Allows data to be transferred over the HTTP protocol.
    • Used to create servers.
    • Used to handle requests from clients.
    • Used to provide responses to requests.
    • import http from 'node:http' const PORT = 8000 const server = http.createServer((request, response) => { response.end('whatever') }) server.listen(PORT, () => console.log(`server is running on port: ${PORT}`))
    • The end method response.end() sends data over HTTP and ends the response. To get a response you need to be running npm start
  • A 200 response is success!
  • The response object
    • Has methods which allow us to:
      • Specify content type
      • set status codes (200, 400 etc.)
      • provide content (html, JSON, images)
    • The write method const server = http.createServer((req, res) => { res.write('whatever') res.end() }) allows you to write seperately from ending. You do still need to end.
  • The Request Response Cycle
    • The client makes an HTTP request to the server and the server sends an HTTP response to the client.
    • Example API: Client makes HTTP request containing (Method: GET, Request Path: /api, and Data: query string/ path params) to the server. The server handles the requestion which could include filtering data, throwing an error, and generating a response. That response is than passed from the server containing the Resourse (JSON), Content-Type (application/json), the Status code (200, 404, etc.), and the Satus message to the client.
  • The Request Object
    • Gives us access to the incoming request. The URL the client used, headers being sent, data being sent, and the method (GET, POST, DELETE).
    • const server = htt.createServer((req, res) => { if (req.url === '/specific-url') { res.write('specific to url') } res.end() })
    • On the request you can get the url req.url,
  • Methods
    • non-exhastive list
      • GET
      • POST
      • DELETE
      • PUT
      • PATCH
    • const server = http.createServer((req, res) => { if (req.method === 'GET') { res.end('This will be sent from the server if the request is a GET method.') } })
  • JSON
    • Human readble
    • HTTP is a text-based protocol. All data transferred between the client and the server must be in the form of strings.
    • To convert JSON to a string you can use stringify: JSON.stringify(dataToConvert)
  • Accessing the database is an async process.
  • Creating the server when waiting for data?
    • const server = http.createServer(async (req, res) => { const dataYouWant = await getDataFromDB(); res.end(JSON.stringify(dataYouWant)) })
  • Setting the Content-Type
    • Common Content-Types (Mime types)
      • application.json
      • text/html
      • text.css
      • application/javascript
    • To change the Content-Type of a response: res.setHeader("Content-Type", "application/json") . Note: it is case sensitive.
  • Setting the StatusCode Property
    • res.statusCode = 200
  • Not Found?
    • const server= http.createServer(async (req, res) => { if (res.url = "/bad-url") { res.setHeader('content-Type', 'application/json') res.statusCode = 404 res.end(JSON.stringify({error: "not found", message: "The requested route doesn't exist"})) } })
  • Path Parameters
    • if (req.url.startsWith('/api/whatever') && req.method === 'GET') { const filteredBy = req.url.split('/').pop() const filteredData = data.filter((obj) => { return obj[filteredBy].toLowerCase() === filteredTo.toLowerCase() }) res.setHeader('Content-Type', 'application/json') res.statusCode = 200 res.end(JSON.stringify(filteredData)) }
  • Query Params
    • ? introduces the query string.
    • key=value
    • & is breaking between key value pairs.
    • /api?key1=value1&key2=value2
    • Turning query params into an object: const urlObj = new URL(req.url, `http://${req.headers.host}`) will return an object including searchParams. const queryObj = Object.fromEntries(urlObj.searchParams) will return an object of the search params in the search query.