Home  >  Article  >  Web Front-end  >  Detailed explanation of node file batch renaming examples

Detailed explanation of node file batch renaming examples

小云云
小云云Original
2018-01-20 17:45:441866browse

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

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, write content, write 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');
});

dir is the name of the new directory

Read the directory


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

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

Stats method after obtaining file information:

Method Description
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');

Create write stream


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

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

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:

How to use node to implement a function to batch rename files

PHP batch rename a certain Introduction to the implementation method of all files in the folder

php batch rename

The above is the detailed content of Detailed explanation of node file batch renaming examples. 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