Home>Article>Web Front-end> Teach you step by step how to use node.js to batch rename files/directories (practical combat)

Teach you step by step how to use node.js to batch rename files/directories (practical combat)

青灯夜游
青灯夜游 forward
2021-08-23 10:13:12 2644browse

How to batch rename files in Node.js project? This article will introduce to you how to batch rename files and folders usingNode.js.

Teach you step by step how to use node.js to batch rename files/directories (practical combat)

Node.js batch rename files/folders

In work and life, we often encounter the need to rename files. , it can still be done manually for a small number of files, but it is not that simple if there are too many files. [Recommended learning: "nodejs Tutorial"]

In the process of learning Node.js, I learned thefile system moduleof Node.js, so let’s write one Tool function, one command, batch rename files and folders

Let’s briefly learn the built-in module of Node.js: File system

The file system module of Node.js

Node.js's built-in module: fs module, is a tool function used to process files and directories (folders), that is,File system

1. readFile function

fs module'sreadFilefunction: used to read the file content, call the callback function to transfer the parsed content

const { readFile } = require('fs') readFile('iwin621.txt', 'utf8', (error, txt) => { if(error) throw error console.log('iwin621 的文本为: ', txt) })

The first parameter of readFile is the file path, and the second parameter is the character encoding used to decode the file into a string.

If no encoding parameter is passed, Node.js will assume it is Buffer The object

Buffer is an array-like object that contains numbers representing the bytes in the file

2. writeFile function

The writeFile function is used to write the file Write to disk,

const { writeFile } = require('fs') writeFile('iwin621.txt', '这是一串文本内容', err => { if(err) { console.log('写入文件错误: ', err) } else { console.log('File written..') })

3. readdir function

readdir function is used to return the files in the directory, in the form of a string array

4. rename function

As the name suggests, the rename function is used to rename files

4. unlink function

The unlink function is used To delete a file

For more programming-related knowledge, please visit:Programming Video! !

The above is the detailed content of Teach you step by step how to use node.js to batch rename files/directories (practical combat). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete