Here's a simple Node.js program using Express and EJS that recursively scans a directory and serves a nested list of files and folders as a webpage:
- First, install the necessary packages:
npm init -y
npm install express ejs
- Create the main application file app.js:
const express = require('express');
const app = express();
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');
// Set the views directory and the view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Define the route for the directory listing
app.get('/list/:dir(*)', (req, res) => {
const dirPath = path.join(__dirname, req.params.dir);
if (fs.existsSync(dirPath)) {
const listData = getNestedList(dirPath);
res.render('list', { dirPath, listData });
} else {
res.status(404).send('Directory not found');
}
});
// Define the function to recursively get the nested list of a directory
function getNestedList(dirPath) {
const files = fs.readdirSync(dirPath);
const nestedList = [];
files.forEach(file => {
const filePath = path.join(dirPath, file);
if (fs.statSync(filePath).isDirectory()) {
const subList = getNestedList(filePath);
nestedList.push({ name: file, type: 'directory', items: subList });
} else {
nestedList.push({ name: file, type: 'file' });
}
});
return nestedList;
}
// Start the server on port 3000
app.listen(3000, () => console.log('Server started on port 3000'));
- Create a new folder named views and create an EJS template file list.ejs inside it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Directory Listing</title>
</head>
<body>
<h1>Directory Listing: <%= dirPath %></h1>
<ul>
<% listData.forEach(item => { %>
<li>
<% if (item.type === 'directory') { %>
<strong><a href="/list/<%= path.join(dirPath, item.name).substring(__dirname.length) %>"><%= item.name %></a></strong>
<ul>
<% item.items.forEach(subItem => { %>
<li>
<% if (subItem.type === 'file') { %>
<%= subItem.name %>
<% } %>
</li>
<% }) %>
</ul>
<% } else { %>
<%= item.name %>
<% } %>
</li>
<% }) %>
</ul>
</body>
</html>
- Run the application:
node app.js
Now, when you visit http://localhost:3000/list/your_directory_path (replacing your_directory_path with the path of the directory you want to list), you will see a nested list of files and folders.