Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
This example shows how to rename a set of files (the same approach works for moving files, since renaming changes the path).
One use case: in static site generators like Hugo, posts can be single files:
first-post.md
second-post.md
third-post.md
We can also add them to a folder that contains an index.md file:
first-post/
> index.md
second-post/
> index.md
third-post/
> index.md
Using a folder per post makes it easier to add images. Converting many single-file posts to folders by hand is tedious; the following script automates it.
Start by requiring the fs core module (no need to install it):
const fs = require('fs')
Get a reference to the current folder (run the script from the folder you want to change). __dirname is the path of the directory containing the current script.
List all files and folders:
const files = fs.readdirSync(__dirname)
Filter to only .md files:
for (const file of files) {
if (file.endsWith('.md')) {
console.log(file)
}
}
For each filename, create a folder (name without .md) and move the file into it:
fs.mkdirSync(__dirname + '/' + file.replace('.md', ''), { recursive: true })
Then call fs.renameSync() to move the file. The synchronous methods mkdirSync() and renameSync() ensure the folder exists before the file is moved; otherwise the second call could run before the first finishes. (You could use promisify with the async versions; the sync versions keep this example simple.)
fs.renameSync() takes two arguments:
- the current path
- the path we want to move to
The current path is:
__dirname + '/' + file
The path we want to move to is:
__dirname + '/' + file.replace('.md', '') + '/index.md'
Create a folder named after the file (without .md), then move the file into it as index.md:
fs.renameSync(
__dirname + '/' + file,
__dirname + '/' + file.replace('.md', '') + '/index.md'
)
Full script:
const fs = require('fs')
const files = fs.readdirSync(__dirname)
for (const file of files) {
if (file.endsWith('.md')) {
fs.mkdirSync(__dirname + '/' + file.replace('.md', ''), { recursive: true })
fs.renameSync(
__dirname + '/' + file,
__dirname + '/' + file.replace('.md', '') + '/index.md'
)
}
}