How to do it...

Let's suppose we want to have some flag icons served for an application. I did the following:

  1. I created, at the same level as the /out directory into which the output files go, a /flags directory with some subdirectories: /flags/america/north/flags/america/south, and /flags/europe.
  2. I placed some free flag icons by GoSquared, taken from https://www.gosquared.com/resources/flag-icons/ in those directories. For variety, the flags are accessible at the /static path, which doesn't actually exist.
  3. I wrote the following code; this is the basic server from earlier, with just some added code (in bold font) to deal with static files:
// Source file: src/serve_statics.js

/* @flow */
"use strict";

const express = require("express");
const path = require("path");
const app = express();

app.get("/", (req, res) => res.send("Server alive, with Express!"));

app.use(
"/static",
express.static(path.join(__dirname, "../flags"), {
immutable: true,
maxAge: "30 days"
})
);

app.use((err, req, res, next) => {
console.error("Error....", err.message);
res.status(500).send("INTERNAL SERVER ERROR");
});

app.listen(8080, () =>
console.log(
"Mini Express static server ready at http://localhost:8080/!"
)
);
If you want to read more about serving static files, check out Node's documentation at https://expressjs.com/en/starter/static-files.html.

app.use(), in this case, gets a special function, express.static(), which takes care of sending files in the given path, with some headers for caching; let's get into the details:

  • The first parameter to app.use() is the base of the path that the user will select; note that it doesn't need to exist in the actual directory, as in other examples we have seen. We could write app.use() if we want to accept all HTTP methods, by the way.
  • The first parameter to express.static() specifies the path where the files are found. I'm using the path.join() function to find out the actual path: /flags at the same level as /out.
  • The second parameter to express.static() lets you add options; in our case, I'm sending some caching headers so that browsers will know that the file can be safely cached for 30 days.
The format for the maxAge parameter can be in a format understood by the ms package (https://github.com/zeit/ms), which is able to convert date and time strings into the equivalent milliseconds, which is standard for JS.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.12.240