Home Web Front-end JS Tutorial node file batch rename

node file batch rename

Mar 13, 2018 pm 05:14 PM
node document double naming

This time I will bring you the batch renaming of node files. What are the precautions for batch renaming of node files? The following is a practical case, let’s take a look.

In an actual requirement, a batch of files (such as text, pictures) need to be renamed and numbered according to numbers. I just took this opportunity to get familiar with node's fs file operations and wrote a script to batch modify file names.

Requirements

Existing following image files

node file batch rename


Before modification

It is necessary to modify the file names in batches to a unified prefix name and automatically increase the index. The effect after modification is



After modification

node file batch rename

The simplest manual operation is to rename files one by one, but in line with the DRY (Don't repeat yourself) principle, it is better to write a node script to do it.

Research

To perform file operations in node, you need to understand the fs module

There are two ways of synchronous and asynchronous in the fs module

Read files

1

2

3

//异步fs.readFile('test.txt', 'utf-8' (err, data) => {    if (err) {        throw err;

    }    console.log(data);

});//同步let data = fs.readFileSync('test.txt');console.log(data);

Copy after login

Asynchronously read file parameters: file path, encoding method,

Callback function

Write file

1

2

3

fs.writeFile('test2.txt', 'this is text', { 'flag': 'w' }, err => {    if (err) {        throw err;

    }    console.log('saved');

});

Copy after login

Write file parameters : Target file, writing content, writing form, callback function

flag writing method:

r: Reading file

w: Writing file

a : Append

Create directory

1

2

3

fs.mkdir('dir', (err) => {    if (err) {        throw err;

    }    console.log('make dir success');

});

Copy after login

dir is the name of the new directory

Read directory

1

2

3

fs.readdir('dir',(err, files) => {    if (err) {        throw err;

    }    console.log(files);

});

Copy after login

dir is the name of the read directory, files is the directory name Array of file or directory names

Get file information

1

fs.stat('test.txt', (err, stats)=> {    console.log(stats.isFile());         //true})

Copy after login

Stats method after getting file information:


Method

Description

1

2

3

4

5

6

7

stats.isFile()    是否为文件   

stats.isDirectory()    是否为目录   

stats.isBlockDevice()    是否为块设备   

stats.isCharacterDevice()    是否为字符设备   

stats.isSymbolicLink()    是否为软链接   

stats.isFIFO()    是否为UNIX FIFO命令管道   

stats.isSocket()    是否为Socket

Copy after login

Create a read stream

1

let stream = fs.createReadStream('test.txt');

Copy after login

Create a write stream

1

let stream = fs.createWriteStreamr('test_copy.txt');

Copy after login

Development

Development ideas:

Read the source directory

Determine whether the storage directory exists, and create a new directory if it does not exist

Copy files

Determine whether the copied content is a file

Create a read stream

Create a write stream

Link the pipe and write the file content

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

let fs = require('fs'),

    src = 'src',

    dist = 'dist',

    args = process.argv.slice(2),

    filename = 'image',

    index = 0;//show helpif (args.length === 0 || args[0].match('--help')) {    console.log('--help\n \t-src 文件源\n \t-dist 文件目标\n \t-n 文件名\n \t-i 文件名索引\n');    return false;

}

args.forEach((item, i) => {    if (item.match('-src')) {

        src = args[i + 1];

    } else if (item.match('-dist')) {

        dist = args[i + 1];

    } else if (item.match('-n')) {

        filename = args[i + 1];

    } else if (item.match('-i')) {

        index = args[i + 1];

    }

});

fs.readdir(src, (err, files) => {    if (err) {        console.log(err);

    } else {

        fs.exists(dist, exist => {            if (exist) {

                copyFile(files, src, dist, filename, index);

            } else {

                fs.mkdir(dist, () => {

                    copyFile(files, src, dist, filename, index);

                })

            }

        });

    }

});function copyFile(files, src, dist, filename, index) {

    files.forEach(n => {        let readStream,

            writeStream,

            arr = n.split('.'),

            oldPath = src + '/' + n,

            newPath = dist + '/' + filename + index + '.' + arr[arr.length - 1];

        fs.stat(oldPath, (err, stats) => {            if (err) {                console.log(err);

            } else if (stats.isFile()) {

                readStream = fs.createReadStream(oldPath);

                writeStream = fs.createWriteStream(newPath);

                readStream.pipe(writeStream);

            }

        });

        index++;

    })

}

Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Use JS code to create barrage effects

Use H5 canvas to create barrage effects

The above is the detailed content of node file batch rename. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover expired WeChat files? Can expired WeChat files be recovered? How to recover expired WeChat files? Can expired WeChat files be recovered? Feb 22, 2024 pm 02:46 PM

How to recover expired WeChat files? Can expired WeChat files be recovered?

Preparing for removal takes a long time in Windows 11/10 Preparing for removal takes a long time in Windows 11/10 Feb 19, 2024 pm 07:42 PM

Preparing for removal takes a long time in Windows 11/10

Photos cannot open this file because the format is not supported or the file is corrupted Photos cannot open this file because the format is not supported or the file is corrupted Feb 22, 2024 am 09:49 AM

Photos cannot open this file because the format is not supported or the file is corrupted

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Can Tmp format files be deleted?

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk?

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code.

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

What is hiberfil.sys file? Can hiberfil.sys be deleted?

How to install GHO files How to install GHO files Feb 19, 2024 pm 10:06 PM

How to install GHO files

See all articles