Cómo cambiar el nombre de archivos en masa en Node.js

En esta publicación de blog, voy a explicar cómo cambiar el nombre de un conjunto de archivos.

El mismo proceso funciona para mover archivos a otra carpeta, porque cuando cambia el nombre, cambia el nombre de la ruta del archivo.

La motivación para esta tarea fue la siguiente: en Hugo podemos escribir publicaciones de blog como archivos, así:


We can also add them to a folder that contains an index.md file:

  > index.md
  > index.md
  > index.md

The difference is that with folder we can add images and associate them more easily to a blog post.

I could have done the change manually, but I had about 50 files in the folder and I didn’t really want to do that job.

I wanted it to happen automatically.

Let’s start by requiring one core module we’re going to use: fs. As it is a core module, there’s no need to npm install it.

const fs = require('fs')

Then, get a reference to the current folder. I suppose we’re going to run the script in the same folder where we want to perform this change.

__dirname is the variable that always points to the current working folder.

I get a list of all the files and folders:

const files = fs.readdirSync(__dirname)

Then I filter out only the items that end with .md:

for (const file of files) {
  if (file.endsWith('.md')) {

Once we have the file reference, which represents the filename, we can call fs.rename().

This function accepts 3 parameters:

  1. the current path
  2. the path we want to move to
  3. an callback fired if there’s an error

The current path is:

__dirname + '/' + item

The path we want to move to is:

__dirname + '/' + item.replace('.md', '') + '/index.md'

See? We create a new folder from the file name, then we append index.md:

  __dirname + '/' + item,
  __dirname + '/' + item.replace('.md', '') + '/index.md',
  err => {

Here’s the full code:

const fs = require('fs')
const files = fs.readdirSync(__dirname)

for (const file of files) { if (file.endsWith(’.md’)) { fs.rename( __dirname + ‘/’ + item, __dirname + ‘/’ + item.replace(’.md’, ‘’) + ‘/index.md’, err => { console.log(err) } ) } }

Download my free Node.js Handbook

More node tutorials: