Home > Web Front-end > JS Tutorial > How to batch rename node files

How to batch rename node files

小云云
Release: 2018-01-04 10:06:36
Original
1413 people have browsed it

This article mainly introduces the example of the method of batch renaming node files. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

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

The following image files currently exist

The file names need to be modified in batches , become a unified prefix name and automatically increase the index. The effect after modification is

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

Research

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

There are synchronous and asynchronous in the fs module Two ways

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);
Copy after login

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');
});
Copy after login

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

flag writing method:

r: read file
w: write file
a: append

Create directory


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 the directory


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

dir is the directory name to read, files is the file or directory name array under the directory

Get file information


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

Stats method after obtaining file information:

MethodDescription
stats.isFile()Whether it is a file
stats.isDirectory()Whether it is a directory
stats.isBlockDevice()Whether it is a block device
stats.isCharacterDevice()Whether it is a character device
stats.isSymbolicLink()Whether it is a soft link
stats.isFIFO()Whether it is a UNIX FIFO command pipeline
stats.isSocket()Whether to create a read stream for Socket


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

Create write stream


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

Development

Development ideas:

  1. Read the source directory

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

  3. Copy files

  4. Determine whether the copied content is a file

  5. Create a read stream

  6. Create a write stream

  7. Link pipe, write file content


let fs = require('fs'),
  src = 'src',
  dist = 'dist',
  args = process.argv.slice(2),
  filename = 'image',
  index = 0;

//show help
if (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
Effect

Summary


node provides many modules that can help us complete the functional development of different needs, so that javascript is not limited to browsers , trying to write some scripts yourself will help you understand these modules, and it can also improve office efficiency.


Related recommendations:


Introduction to how to batch rename all files in a folder with PHP

Talk about the detailed explanation of the rename method renames

How to use the rename method? Summary of rename method instance usage

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template