0
0
Node.jsframework~10 mins

Why Node.js for server-side JavaScript in Node.js - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the HTTP module in Node.js.

Node.js
const http = require([1]);
Drag options to blanks, or click blank then click option'
A"http"
B"fs"
C"path"
D"url"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a module name unrelated to HTTP like 'fs' or 'path'.
Forgetting to put quotes around the module name.
2fill in blank
medium

Complete the code to create a simple server that listens on port 3000.

Node.js
http.createServer((req, res) => {
  res.end('Hello World');
}).[1](3000);
Drag options to blanks, or click blank then click option'
Aopen
Brun
Clisten
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods like 'start' or 'run' which do not exist on the server object.
Confusing the method with something like 'open'.
3fill in blank
hard

Fix the error in the code to correctly handle asynchronous file reading in Node.js.

Node.js
const fs = require('fs');
fs.readFile('file.txt', [1], (err, data) => {
  if (err) throw err;
  console.log(data.toString());
});
Drag options to blanks, or click blank then click option'
Autf8
Btrue
Cbuffer
Dsync
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 'true' or 'sync' which are not valid encodings.
Omitting the encoding and trying to use toString() without it.
4fill in blank
hard

Fill both blanks to create a simple Express server that responds with 'Hi!' on the root URL.

Node.js
const express = require('express');
const app = express();
app.[1]('/', (req, res) => {
  res.[2]('Hi!');
});
app.listen(3000);
Drag options to blanks, or click blank then click option'
Aget
Bpost
Csend
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'post' instead of 'get' for the root URL.
Using 'write' instead of 'send' to respond.
5fill in blank
hard

Fill all three blanks to create a Node.js server that reads a file and sends its content as a response.

Node.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
  fs.readFile([1], [2], (err, data) => {
    if (err) {
      res.statusCode = 500;
      res.end('Error');
      return;
    }
    res.setHeader('Content-Type', [3]);
    res.end(data);
  });
}).listen(8080);
Drag options to blanks, or click blank then click option'
A'index.html'
B'utf8'
C'text/html'
D'style.css'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a CSS file instead of an HTML file.
Omitting the encoding or using wrong encoding.
Setting wrong content type like 'text/css'.