Node.js app with Nunjucks (Part 2)

In the first part of this tutorial, we created a basic Node.js app to use for serving pages built using Nunjucks. Now it’s time to configure Nunjucks and our app to use it.

Configuration

Firstly, install Nunjucks, and to use the file watcher built-in to Nunjucks, Chokidar, a cross-platform file-watching library, must be installed as well.

You have to also install the relevant type definition package.

Following the model-view-controller software design pattern, create a views subdirectory in the src directory. This is where your template files will be located. Then in the index.ts file set path to it.

Also remember about importing the Node.js path module (here is more about it if you are interested in details).

Next, create a Nunjucks loader, which is an object that takes a template name and loads it from a source, with a path to templates as an argument.

Also, create an object with the loader options. You really only need two: watch, which reloads templates when they are changed (server-side), and noCache, which will determine if the cache is used or templates will be recompiled every single time (see the documentation).

Of course, remember to add relevant entries to the .env file.

Finally, create a new instance of Nunjucks’s Environment class with the loader and its options.

Then install Nunjucks as the rendering engine for the Express app.

You also need to provide the view engine, which is the file extension of your template files. You can use njk, which is the one adopted by the Nunjucks community, or html, but in fact, you are free to use any file extension you wish for your Nunjucks template files since any will work.

To check if the configuration works, create a simple template in the views directory with the name index.njk.

Then create a controllers directory in the src directory, and inside it, create an indexController.ts file with a simple function that will call Nunjucks’s render function available in the response parameter. It takes the name of the template and an object with properties that will be used in the template to substitute the tags with the provided texts. You have to ensure that the property keys are the same as the tags in the template.

Next, you have to import it into index.ts

and provide as a parameter to the get request instead of the previously used arrow function.

Before you can run the app, you have to modify the scripts in package.json. First, add a new script called build that will run the preexisting clean script, which removes the build directory, then the compile script, which will run the TypeScript Compiler (tsc), and finally copy recursively the views directory.

Then modify the start script, replacing the compile script with the build script, so it’s as follows:

Now you can run your app. Happy coding!

Node.js app with Nunjucks (Part 1)

The main focus of this tutorial is to learn how to use Nunjucks, a powerful templating language for JavaScript. However, before we can dive into Nunjucks itself, it is first important to create a basic Node.js app to use for serving pages built using Nunjucks. Thus, this is what the first part of this tutorial is all about.

Creating a basic Node.js app

To create a Node.js app, first create a new project directory and enter it.

The next step is optional, although it is always good idea to use version control, even if only for practice.

Once that’s done, initiate a new npm package using npm, the default package manager for Node.js. If you add the -y flag, it will use the default values as explained in this blog post.

To further save time and effort, install Google TypeScript Style (GTS), which will allow you to automatically set up a simple TypeScript project while providing a style guide, a linter, and automatic code correction.

Then initialise TypeScript project using GTS.

This will create all the configuration files with the basic default configuration for TypeScript and Lint. To further tune the project, add to the compilerOptions in tsconfig.json the following options:

The first one specifies ECMAScript target version, the second one sets the module system for the program, the third one fixes some problems with imports and the last one prevents TypeScript from assuming type any if type annotation is not present. For reference see the documentation available at https://www.typescriptlang.org/tsconfig.

Next install ts-node, which is a TypeScript execution engine and REPL for Node.js

and add start script to package.json

For convenience, also install nodemon, a tool that will help develop your node application by automatically restarting it when file changes are detected

and add the relevant script to the package.json

Now you can run your basic app from the terminal with either npm start or npm run start:dev. But before you do that, replace the default content of the src/index.ts file with the following code:

You have to also install a web framework for Node.js called Express and Dotenv, a module that loads environment variables from a .env file into process.env, and type definition packages

and add a .env file in the root directory of the project with the PORT variable set

Now all is ready. Happy coding!

Journal (The gift of life)

I never asked to be born. It was forced upon me by a moment of mindless lust, later sugarcoated by religion with the phrase “the gift of life.” The problem is, unlike an unwanted Christmas gift, I can’t simply toss it away. Both nature and society have made sure to hold me hostage as long as possible and to produce further victims of this vicious circle. Now that I’ve finally realised this, I know why Merry Christmas sounds like an insult.

Journal (Leave the story where it ended)

I promised myself that I would write something in this journal every day. That’s why I call it a journal and not a diary. But yesterday I got so into the anime series that I couldn’t stop watching it until I watched the entire first season. It’s called Horimiya. I’ve seen it at least three times this past winter, when I had a period of fascination with the anime genre and watched nothing but anime for about six months. I have to admit, I like it just as much as I did when I first saw it.

Later, in the evening

So, I finished watching the second season, which is new, and I’m disappointed. Not that it was bad, but I expected something different—a continuation or something along this line. Instead, it was like watching footnotes to the first season or miscellaneous. I think sometimes it’s better to leave a story where it originally ended rather than try to squeeze some extra cash out of it with artificial prolongations.

Journal (The world of the one percent)

I have always had this funny feeling that when someone accuses remote workers that they “don’t work as hard,” there is more to it. But it’s not rocket science to figure out what’s behind such words coming from the mouth of someone like Steve Schwarzman, the boss of the world’s biggest commercial landlord—it’s money. It’s always money. Welcome to the world of the one percent. I bet Mr. Schwarzman doesn’t give a damn about the productivity of those working from home. The only thing he cares about is the hard cash that he loses when his office buildings are empty because no one needs to rent them if the staff of many companies work remotely. And just so you know, Mr. Schwarzman, not only do we work as hard, but we are actually more productive when finally free from all the unnecessary distractions inherent in the office. But that would be enough about Mr. Schwarzman. He doesn’t deserve even that much airtime.

Journal (I’m a city dweller)

I watched Jenny’s Wedding today. Nothing special, really. Apart from the fact that it’s about a lesbian couple, it’s just another romcom spiced with a pinch of light drama. But there was one thing there that made me think. The protagonist’s sister, played by Grace Gummer, realises that the grass in front of her house is always dead, and then she has an epiphany: “Happy people do not have dead grass.” It ends badly for her husband (not that I pity him—he was rather obnoxious). The problem is that I hate grass. Not in general, as there is nothing more pleasant than a stroll on the meadow in summer, but the lawn in front of the house is the essence of artificiality. I hate Saturday gymnastics with a lawnmower and the endless fight with moss and so-called weeds. When I lived in a house with a lawn, I envied my neighbour’s elegantly tiled front yard. But does this make me a bad person, a social outcast, or a less desirable life partner? I’m a city dweller, that’s all. Suburbs are not for me.

Journal (The sound of the waves)

What do you do when you realise you are not going to be a great poet one day? After thirty years of writing poetry, you finally give up, make a note of it in your journal, and move on. Simple as that. After all, there is more to life than putting together a stanza, even a great one. And if, in your case, it’s decent at best, what’s the point? Instead of wasting hours in your room trying to find the right onomatopoeia, wouldn’t it be better to listen to the sound of the waves while walking on the beach?

Journal (Conversations with Other Women)

I adore Helena Bonham Carter, but for whatever reason, any time I see her, I picture a crazy cat lady. But this aside, I just watched Conversations with Other Women, and there is a one-liner there that I just love. It goes like this: a woman played by Bonham Carter says, “You’re just a dirty old pervert,” to which a man played by Aaron Eckhart replies, “Yes, I am. But I’m your dirty old pervert.” If only I had a chance to say something like that.

Journal (There were never so many poetasters as now)

“Since Ronsard and Du Bellay have given reputation to our French poesy, every little dabbler, for aught I see, swells his words as high, and makes his cadences very near as harmonious as they: ‘Plus sonat, quam valet.’ [‘More sound than sense’—Seneca, Ep., 40.] For the vulgar, there were never so many poetasters as now; but though they find it no hard matter to imitate their rhyme, they yet fall infinitely short of imitating the rich descriptions of the one, and the delicate invention of the other of these masters.” (from The Essays of Montaigne—Volume 05 by Michel de Montaigne, translated by Charles Cotton)

Reading his words, I wonder what Montaigne would say about the state of poetry in our times, as not only has it evolved in form but it has also democratised, and today in France alone, probably more people write poetry than were educated in that country in his time. But reading this passage, I feel that they are as relevant now as they were then. If I happen to stumble upon a poem, especially one published online, I almost never find any satisfaction in reading it, let alone being impressed, and that’s also why I’ve stopped writing poetry myself. But enough about that because the sun finally came out after the storm Babet, so it’s time to go outside.