As with any kind of app, there are difficult issues to solve when we write Node apps. In this article, we’ll look at some solutions to common problems when writing Node apps.
Route All Requests to index.html with Express
We can route all requests to index.html
in an Express app by using the *
wildcard to listen to all requests.
For instance, we can write:
const express = require('express');
const path= require('path');
const server = express();
server.use('/public', express.static(path.join(__dirname, '/assets')))
server.get('/hello', (req, res) => {
res.send('hello');
})
server.get('/*', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
})
const port = 8000;
server.listen(port);
We have an Express app that serves the /assets
folder with the /public
route. Then we define a GET route that’s not a catch-all route to listen to GET requests with that path. Then we define our catch-all route to render index.html
. Anything that doesn’t match /public
or /hello
rendersindex.html
.
Re-throwing Exception and not Losing Stack Trace
We can rethrow an exception and not lose the stack trace by rethrowing the error object in the catch
clause.
For instance, we can write:
try {
//...
throw new Error("error");
//...
} catch(err) {
err.message = `error: ${err.message}`;
throw err;
}
We run something that throws an error in the try
block.
Then in the catch
block, we change the err.message
as we want to and keep the stack trace.
Then we throw the err
object again after it’s modified.
Read JSON File Content with require vs fs.readFile
require
reads the JSON file content synchronously.
The file is parsed without any extra work.
For instance, if we have:
const obj = require('./someJson');
then we read the someJson.json
file and assign the returned value to obj
.
We don’t need the .json
extension and it’s parsed without any code.
If we use readFile
, then we read the JSON file asynchronously.
Also, we’ve to parse the text with JSON.parse
to convert it to an object.
For example, we can write:
const fs = require('fs');
fs.readFile('/path/test.json', 'utf8', (err, data) => {
if (err) {
return console.error(err);
}
const obj = JSON.parse(data);
});
We pass in the path as the first argument.
The encoding is the 2nd argument.
The callback is the 3rd argument.
data
has the data, which is in a string.
We used JSON.parse
to parse into an object.
We can also do the same thing synchronously with readFileSync
.
For instance, we can write:
const fs = require('fs');
const json = JSON.parse(fs.readFileSync('/path/test.json', 'utf8'));
We pass in the path and encoding and it’ll return the JSON string.
Then we call JSON.parse
to parse the string.
We can use require
to cache the object.
readFileSync
is faster out of the 3 choices according to https://github.com/jehy/node-fastest-json-read/runs/416637981?check_suite_focus=true
readFile
is the slowest but doesn’t block the event loop.
Basic Web Server with Node.js and Express for Serving HTML File and Assets
We can use the connect
package to make a basic web serve to serve static files.
To install it, we run:
npm install connect
Then in our code file, we can write:
const connect = require('connect');
const port = 1234;
connect.createServer(connect.static(__dirname)).listen(port);
We call createServer
to create the webserver.
connect.static
is a middleware to let us serve the static files.
listen
selects the port that we listen to requests from.
With Express, we can write:
const express = require('express');
const app = express();
const http = require('http');
const path = require('path');
const httpServer = http.Server(app);
app.use(express.static(path.join(__dirname, '/assets')));
app.get('/', (req, res) => {
res.sendfile(path.join(__dirname, '/index.html'));
});
app.listen(3000);
We use the express.static
middleware to serve static files.
Then we can access them from index.html
, where we access the assets
folder.
Get a List of Files in Chronological Order
We can sort a list of files that are returned from readdirSync
by using the sort
method.
For instance, we can write:
const fs = require('fs');
const path = require('path');
const dir = './';
const files = fs.readdirSync(dir);
files.sort((a, b) => {
return fs.statSync(path.join(dir, a)).mtime.getTime() - fs.statSync(path.join(dir, b).mtime.getTime();
});
In the sort
callback, we use getTime
to get the timestamp of when the files are modified.
We subtract them to sort in ascending order.
We can do the same thing with readFile
in the callback.
Conclusion
We can serve static files and route requests to static pages. Files can be sorted once they’re read. Error objects can be modified and rethrown. JSON can be read with various methods.