В этом сообщении блога я собираюсь объяснить, как переименовать набор файлов.
Тот же процесс работает для перемещения файлов в другую папку, потому что при переименовании вы переименовываете путь к файлу.
Мотивация для этой задачи заключалась в следующем: в Hugo мы можем писать сообщения в блогах в виде файлов, например:
first-post.md
second-post.md
third-post.mdWe can also add them to a folder that contains an index.md
file:
first-post/
> index.md
second-post/
> index.md
third-post/
> index.mdThe 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')) {
console.log(file)
}
}
Once we have the file
reference, which represents the filename, we can call fs.rename()
.
This function accepts 3 parameters:
- the current path
- the path we want to move to
- 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
:
fs.rename(
__dirname + '/' + item,
__dirname + '/' + item.replace('.md', '') + '/index.md',
err => {
console.log(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:
- An introduction to the npm package manager
- Introduction to Node.js
- HTTP requests using Axios
- Where to host a Node.js app
- Interact with the Google Analytics API using Node.js
- The npx Node Package Runner
- The package.json guide
- Where does npm install the packages?
- How to update Node.js
- How to use or execute a package installed using npm
- The package-lock.json file
- Semantic Versioning using npm
- Should you commit the node_modules folder to Git?
- Update all the Node dependencies to their latest version
- Parsing JSON with Node.js
- Find the installed version of an npm package
- Node.js Streams
- Install an older version of an npm package
- Get the current folder in Node
- How to log an object in Node
- Expose functionality from a Node file using exports
- Differences between Node and the Browser
- Make an HTTP POST request using Node
- Get HTTP request body data using Node
- Node Buffers
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use the Node.js REPL
- Node, accept arguments from the command line
- Output to the command line using Node
- Accept input from the command line in Node
- Uninstalling npm packages with `npm uninstall`
- npm global or local packages
- npm dependencies and devDependencies
- The Node.js Event Loop
- Understanding process.nextTick()
- Understanding setImmediate()
- The Node Event emitter
- Build an HTTP Server
- Making HTTP requests with Node
- The Node fs module
- HTTP requests in Node using Axios
- Reading files with Node
- Node File Paths
- Writing files with Node
- Node file stats
- Working with file descriptors in Node
- Working with folders in Node
- The Node path module
- The Node http module
- Using WebSockets with Node.js
- The basics of working with MySQL and Node
- Error handling in Node.js
- The Pug Guide
- How to read environment variables from Node.js
- How to exit from a Node.js program
- The Node os module
- The Node events module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to remove a file with Node.js
- How to get the last updated date of a file using Node.js
- How to determine if a date is today in JavaScript
- How to write a JSON object to file in Node.js
- Why should you use Node.js in your next project?
- Run a web server from any folder
- How to use MongoDB with Node.js
- Use the Chrome DevTools to debug a Node.js app
- What is pnpm?
- The Node.js Runtime v8 options list
- How to fix the "Missing write access" error when using npm
- How to enable ES Modules in Node.js
- How to spawn a child process with Node.js
- How to get both parsed body and raw body in Express
- How to handle file uploads in Node.js
- What are peer dependencies in a Node module?
- How to write a CSV file with Node.js
- How to read a CSV file with Node.js
- The Node Core Modules
- Incrementing multiple folders numbers at once using Node.js
- How to print a canvas to a data URL
- How to create and save an image with Node.js and Canvas
- How to download an image using Node.js
- How to mass rename files in Node.js
- How to get the names of all the files in a folder in Node
- How to use promises and await with Node.js callback-based functions
- How to test an npm package locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Serve an HTML page using Node.js
- How to solve the `util.pump is not a function` error in Node.js