Home >Web Front-end >JS Tutorial >node file batch rename

node file batch rename

php中世界最好的语言
php中世界最好的语言Original
2018-03-13 17:14:071644browse

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

//异步fs.readFile('test.txt', 'utf-8' (err, data) => {    if (err) {        throw err;
    }    console.log(data);
});//同步let data = fs.readFileSync('test.txt');console.log(data);

Asynchronously read file parameters: file path, encoding method,

Callback function

Write file

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

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

flag writing method:

r: Reading file

w: Writing file

a : Append

Create directory

fs.mkdir('dir', (err) => {    if (err) {        throw err;
    }    console.log('make dir success');
});

dir is the name of the new directory

Read directory

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

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

Get file information

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

Stats method after getting file information:


Method

Description

stats.isFile()    是否为文件    
stats.isDirectory()    是否为目录    
stats.isBlockDevice()    是否为块设备    
stats.isCharacterDevice()    是否为字符设备    
stats.isSymbolicLink()    是否为软链接    
stats.isFIFO()    是否为UNIX FIFO命令管道    
stats.isSocket()    是否为Socket

Create a read stream

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

Create a write stream

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

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

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++;
    })
}

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:
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