iTranslated by AI
Building a local server to serve static files with Express
Overview
In this article, I will introduce a sample code for setting up a local server for testing that returns static XML files.
This is something I frequently use in my professional work, as it is useful for testing general functions that involve reading files from the server-side (setting up a mock server).
In a previous article, I also covered setting up a mock server using json-server.
Prerequisites
- There are production and development environments, each containing
test1.xmlandtest2.xml. - Returns development XML for
/xml/dev/test1.xml. - Returns production XML for
/xml/product/test2.xml. - The structure should be somewhat easy to extend when similar XML or other files are added in the future.
-
Nodeis already installed.
Installation
We will use the familiar express.
yarn add express
Directory Structure
The directory structure is shown below.
From here on, we will mainly modify server.js.
The assumption is that development files are stored in dev, and production files are stored in product.
.
├── server.js
├── dev
│ ├── test1.xml
│ └── test2.xml
└── product
├── test1.xml
└── test2.xml
The following is server.js.
var express = require("express");
var path = require("path");
var app = express();
// Base endpoint for development environment
const devPath = "/xml/dev";
// Base endpoint for production environment
const productPath = "/xml/product";
// File path for development environment
const __devDir = "/dev";
// File path for production environment
const __productDir = "/product";
var server = app.listen("3000", function () {
console.log("Listening to PORT --> " + server.address().port);
});
// dev/test1.xml
app.get(`${devPath}/test1`, function (req, res, next) {
res.contentType("application/xml");
res.sendFile(path.join(__dirname, `${__devDir}/test1.xml`));
});
// dev/test2.xml
app.get(`${devPath}/test2`, function (req, res, next) {
res.contentType("application/xml");
res.sendFile(path.join(__dirname, `${__devDir}/test2.xml`));
});
// product/test1.xml
app.get(`${productPath}/test1`, function (req, res, next) {
res.contentType("application/xml");
res.sendFile(path.join(__dirname, `${__productDir}/test1.xml`));
});
// product/test2.xml
app.get(`${productPath}/test2`, function (req, res, next) {
res.contentType("application/xml");
res.sendFile(path.join(__dirname, `${__productDir}/test2.xml`));
});
Startup
Once you have created the file, start it with the following command.
node server.js
Now, when you access something like localhost:3000/xml/dev/test1, the target file will be returned.
Summary
In this article, I introduced how to set up a local server using express that returns any static files.
This is quite useful when you need to perform testing while making minor adjustments to the files on the server side.
I hope this information is helpful.
Discussion