Hướng dẫn nodejs rename all files in folder - nodejs đổi tên tất cả các tệp trong thư mục

Hướng dẫn nodejs rename all files in folder - nodejs đổi tên tất cả các tệp trong thư mục

Trong bài viết này, tôi sẽ chỉ cho bạn cách đổi tên tất cả các tệp trong một thư mục bằng Node.js.

Bài viết này đã xuất hiện, bởi vì tôi đã được cung cấp một thư mục hình ảnh PNG từ một nhà thiết kế với cấu trúc tên tệp không nhất quán.

Ví dụ:


images
  - image_Test1.png
  - backgroundImage-hero.png
  - bacgrkound-Image-Hero-2.png
  - Another-image-file.png

Đây là cách tôi đã làm điều đó.

Giải pháp: Sử dụng fs.readDirsync và fs.rename để đổi tên tệp


const { readdirSync, rename } = require('fs');
const { resolve } = require('path');

// Get path to image directory
const imageDirPath = resolve(__dirname, '[imgs_folder_name]');

// Get an array of the files inside the folder
const files = readdirSync(imageDirPath);

// Loop through each file that was retrieved
files.forEach(file => rename(
  imageDirPath + `/${file}`,
  imageDirPath + `/${file.toLowerCase()}`,
  err => console.log(err)
));

Hãy cùng làm một sự cố mã.

Bạn cần phải nhập 2 công cụ tiện ích từ mô -đun


const { readdirSync, rename } = require('fs');
const { resolve } = require('path');

// Get path to image directory
const imageDirPath = resolve(__dirname, '[imgs_folder_name]');

// Get an array of the files inside the folder
const files = readdirSync(imageDirPath);

// Loop through each file that was retrieved
files.forEach(file => rename(
  imageDirPath + `/${file}`,
  imageDirPath + `/${file.toLowerCase()}`,
  err => console.log(err)
));
0 từ nút.


const { readdirSync, rename } = require('fs');


const { readdirSync, rename } = require('fs');
const { resolve } = require('path');

// Get path to image directory
const imageDirPath = resolve(__dirname, '[imgs_folder_name]');

// Get an array of the files inside the folder
const files = readdirSync(imageDirPath);

// Loop through each file that was retrieved
files.forEach(file => rename(
  imageDirPath + `/${file}`,
  imageDirPath + `/${file.toLowerCase()}`,
  err => console.log(err)
));
1 - Đọc nội dung của thư mục đồng bộ và trả về tên của tất cả các tệp bên trong thư mục theo định dạng mảng.


// Get path to image directory
const files = readdirSync(path_to_directory);


const { readdirSync, rename } = require('fs');
const { resolve } = require('path');

// Get path to image directory
const imageDirPath = resolve(__dirname, '[imgs_folder_name]');

// Get an array of the files inside the folder
const files = readdirSync(imageDirPath);

// Loop through each file that was retrieved
files.forEach(file => rename(
  imageDirPath + `/${file}`,
  imageDirPath + `/${file.toLowerCase()}`,
  err => console.log(err)
));
2 - sẽ đổi tên tệp từ đường dẫn cũ sang đường dẫn mới mà nó đưa ra. Nếu tệp tồn tại trong đường dẫn mới, nó sẽ ghi đè nội dung.


rename(old_path, new_path, callback)

Khi tên tệp được truy xuất và chúng tôi đã lưu trữ đường dẫn đến thư mục trong một biến. Tôi sẽ sử dụng


const { readdirSync, rename } = require('fs');
const { resolve } = require('path');

// Get path to image directory
const imageDirPath = resolve(__dirname, '[imgs_folder_name]');

// Get an array of the files inside the folder
const files = readdirSync(imageDirPath);

// Loop through each file that was retrieved
files.forEach(file => rename(
  imageDirPath + `/${file}`,
  imageDirPath + `/${file.toLowerCase()}`,
  err => console.log(err)
));
3 để lặp qua mỗi tên tệp để tôi có thể đổi tên nó theo cách tôi muốn.


// Loop through each file that was retrieved
files.forEach(file => {
  const oldPath = imageDirPath + `/${file}`;

  // lowercasing the filename
  const newPath = imageDirPath + `/${file.toLowerCase()}`;

  // Rename file
  rename(
    oldPath,
    newPath,
    err => console.log(err)
  );
});

Công cụ khá dễ dàng. Mã hóa hạnh phúc!

Tôi thích tweet về Node.js và đăng các đoạn mã hữu ích. Theo tôi ở đó nếu bạn cũng muốn một số!

Tôi có một thư mục có nhiều tệp cho Ex. Các tệp có tên Old.html, Old.txt, Old.json và tôi muốn đổi tên tất cả các tệp này thành new.html, new.txt, new.json. Có bất kỳ phương pháp nào có trong nút JS mà tôi có thể sử dụng ở đây không?

hỏi ngày 25 tháng 2 năm 2020 lúc 10:58Feb 25, 2020 at 10:58

2

Đây là những gì bạn đang tìm kiếm:

const { join, extname, basename } = require('path');
const { readdirSync, renameSync } = require('fs');

for (const oldFile of readdirSync(pathToOldFolder)) {
    const extension = extname(oldFile);
    const name = basename(oldFile, extension);
    if (name === 'old') {
        renameSync(join(pathToOldFolder, oldFile), join(pathToOldFolder, 'new' + extension));
    }
}

Hướng dẫn nodejs rename all files in folder - nodejs đổi tên tất cả các tệp trong thư mục

dhilt

Phim thương hiệu vàng 17K863 Huy hiệu bạc78 Huy hiệu đồng8 gold badges63 silver badges78 bronze badges

Đã trả lời ngày 25 tháng 2 năm 2020 lúc 11:02Feb 25, 2020 at 11:02

BenbenBen

2.9003 huy hiệu vàng16 Huy hiệu bạc 30 Huy hiệu Đồng3 gold badges16 silver badges30 bronze badges

Bạn có thể sử dụng mô -đun FS?

Sử dụng các mục sau để truy xuất danh sách các tệp

fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
});

Sau đó lặp lại chúng để đổi tên các tệp

fs.rename('oldFile.txt', 'newFile.txt', (err) => {
  if (err) throw err;
  console.log('Rename complete!');
});

Đã trả lời ngày 25 tháng 2 năm 2020 lúc 11:02Feb 25, 2020 at 11:02

Benben

2.9003 huy hiệu vàng16 Huy hiệu bạc 30 Huy hiệu Đồng

Bạn có thể sử dụng mô -đun FS?

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p].split(".")[0] + obj[p].split(".")[1], '/path/to/' + 'new' + obj[p].split(".")[1], function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

Sử dụng các mục sau để truy xuất danh sách các tệpFeb 25, 2020 at 11:05

Hướng dẫn nodejs rename all files in folder - nodejs đổi tên tất cả các tệp trong thư mục