Work on explaining how modules work to describe how the HSP pattern came to be.
This commit is contained in:
parent
02ce8e802c
commit
ce6bf28804
@ -20,3 +20,46 @@ I am going to be talking about this pattern in relationship to JavaScript and wh
|
|||||||
## The Application
|
## The Application
|
||||||
|
|
||||||
Like the previous post, I talked about building this blog with Bun and Hono. I am going to do the same here, however the application we are going to build is the all time classic - The TODO Application.
|
Like the previous post, I talked about building this blog with Bun and Hono. I am going to do the same here, however the application we are going to build is the all time classic - The TODO Application.
|
||||||
|
|
||||||
|
## JavaScript
|
||||||
|
|
||||||
|
One of the important things about JavaScript that alluded me for far too long was how the modules actually worked with Node.js. A module before ES6 was simply a JavaScript file that declares a `module.exports` value with the code you want to expose to other modules with the `require` function. Like so:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function doSomething() {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = doSomething;
|
||||||
|
```
|
||||||
|
_`example.js`_
|
||||||
|
|
||||||
|
Then we can pull in `doSomething` with `require`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const doSomething = require('./example');
|
||||||
|
```
|
||||||
|
_`index.js`_
|
||||||
|
|
||||||
|
I don't know why I didn't know this, but the code in the `example.js` file is evaluated **and** run during the `require()` call.
|
||||||
|
|
||||||
|
In my past life I would try and build a Singleton class for holding onto an application's Connection Pool to a database. But because of how the Modules in Node.js work, we only need to instantiate the Pool and export it. Here's an example of how we can set up a single pool using the MariaDB official package:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const mariadb = require('mariadb');
|
||||||
|
|
||||||
|
const config = { ... };
|
||||||
|
const pool = mariadb.createPool(config);
|
||||||
|
|
||||||
|
module.eports = pool;
|
||||||
|
```
|
||||||
|
_`pool.js`_
|
||||||
|
|
||||||
|
Now the connection pool is only created once and you can require this
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user