node loop files and push to array to display on screen with nunjucks

Node Loop Files and Push to Array to Display on Screen with Nunjucks

Introduction

When working with Node.js, it is common to work with files and arrays. In this guide, we will explore how to loop through files in a directory, push them into an array, and display them on the screen using Nunjucks.

Step 1: Import Packages

The first step is to import the necessary packages - fs, which is a built-in package for reading files and nunjucks for rendering templates. Here's how:


const fs = require('fs');
const nunjucks = require('nunjucks');

Step 2: Read Files from Directory

The next step is to read the files from a directory. We can do this using the fs.readdir function. Here's how:


const files = fs.readdirSync('path/to/directory');

The 'path/to/directory' should be replaced with the actual path to the directory you want to read.

Step 3: Loop through Files and Push to Array

Once we have the files in an array, we can loop through them and push them into another array. Here's how:


const fileArray = [];
for (const file of files) {
  const content = fs.readFileSync(`path/to/directory/${file}`);
  fileArray.push(content);
}

The 'path/to/directory' should be replaced with the actual path to the directory you want to read.

Step 4: Render Template with Nunjucks

Now that we have the files in an array, we can render a template using Nunjucks. Here's how:


const template = fs.readFileSync('path/to/template.njk', 'utf8');
const renderedTemplate = nunjucks.renderString(template, { files: fileArray });

The 'path/to/template.njk' should be replaced with the actual path to the Nunjucks template you want to use. The { files: fileArray } is the context object that is passed to the template.

Step 5: Display Result on the Screen

Finally, we can display the result on the screen. Here's how:


const resultDiv = document.getElementById('result');
resultDiv.innerHTML = renderedTemplate;

The 'result' should be replaced with the ID of the HTML div element where you want to display the result.

Alternative Approach

An alternative approach to Step 3 is to use the fs.readdirSync function with the map function. Here's how:


const fileArray = fs.readdirSync('path/to/directory')
  .map(file => fs.readFileSync(`path/to/directory/${file}`));

This approach reads the files from the directory, maps them to an array of file contents, and returns the array in one line of code.

Conclusion

In this guide, we explored how to loop through files in a directory, push them into an array, and display them on the screen using Nunjucks. We also looked at an alternative approach to looping through the files. This is a useful technique when working with Node.js and Nunjucks templates.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe