Đối với tất cả các ví dụ bên dưới, bạn cần nhập các mô -đun FS và PATH:
const fs = require['fs'];
const path = require['path'];
Đọc các tập tin không đồng bộ
function readFiles[dir, processFile] {
// read directory
fs.readdir[dir, [error, fileNames] => {
if [error] throw error;
fileNames.forEach[filename => {
// get current file name
const name = path.parse[filename].name;
// get current file extension
const ext = path.parse[filename].ext;
// get current file path
const filepath = path.resolve[dir, filename];
// get information about the file
fs.stat[filepath, function[error, stat] {
if [error] throw error;
// check if the current path is a file or a folder
const isFile = stat.isFile[];
// exclude folders
if [isFile] {
// callback, do something with the file
processFile[filepath, name, ext, stat];
}
}];
}];
}];
}
Usage:
// use an absolute path to the folder where files are located
readFiles['absolute/path/to/directory/', [filepath, name, ext, stat] => {
console.log['file path:', filepath];
console.log['file name:', name];
console.log['file extension:', ext];
console.log['file information:', stat];
}];
Đọc các tệp đồng bộ, lưu trữ trong mảng, sắp xếp tự nhiên
/**
* @description Read files synchronously from a folder, with natural sorting
* @param {String} dir Absolute path to directory
* @returns {Object[]} List of object, each object represent a file
* structured like so: `{ filepath, name, ext, stat }`
*/
function readFilesSync[dir] {
const files = [];
fs.readdirSync[dir].forEach[filename => {
const name = path.parse[filename].name;
const ext = path.parse[filename].ext;
const filepath = path.resolve[dir, filename];
const stat = fs.statSync[filepath];
const isFile = stat.isFile[];
if [isFile] files.push[{ filepath, name, ext, stat }];
}];
files.sort[[a, b] => {
// natural sort alphanumeric strings
// //stackoverflow.com/a/38641281
return a.name.localeCompare[b.name, undefined, { numeric: true, sensitivity: 'base' }];
}];
return files;
}
Usage:
// return an array list of objects
// each object represent a file
const files = readFilesSync['absolute/path/to/directory/'];
Đọc các tệp async bằng lời hứa
Thông tin thêm về Promisify trong bài viết này.
const { promisify } = require['util'];
const readdir_promise = promisify[fs.readdir];
const stat_promise = promisify[fs.stat];
function readFilesAsync[dir] {
return readdir_promise[dir, { encoding: 'utf8' }]
.then[filenames => {
const files = getFiles[dir, filenames];
return Promise.all[files];
}]
.catch[err => console.error[err]];
}
function getFiles[dir, filenames] {
return filenames.map[filename => {
const name = path.parse[filename].name;
const ext = path.parse[filename].ext;
const filepath = path.resolve[dir, filename];
return stat[{ name, ext, filepath }];
}];
}
function stat[{ name, ext, filepath }] {
return stat_promise[filepath]
.then[stat => {
const isFile = stat.isFile[];
if [isFile] return { name, ext, filepath, stat };
}]
.catch[err => console.error[err]];
}
Usage:
readFiles['absolute/path/to/directory/']
// return an array list of objects
// each object is a file
// with those properties: { name, ext, filepath, stat }
.then[files => console.log[files]]
.catch[err => console.log[err]];
Lưu ý: Trả về undefined
cho các thư mục, nếu bạn muốn bạn có thể lọc chúng ra: return undefined
for folders, if you want you can filter them out:
readFiles['absolute/path/to/directory/']
.then[files => files.filter[file => file !== undefined]]
.catch[err => console.log[err]];
node.js fs Bạn có cần phải có tất cả các tệp có trong thư mục hay bạn muốn quét một thư mục cho các tệp bằng Node.js, sau đó bạn đang ở đúng trang web vì trong NodeJS này cách hướng dẫn, chúng tôi sẽ học cách lấy danh sách của tất cả các tệp trong một thư mục trong node.js.How to get the list of all files in a directory in Node.js. Chúng tôi sẽ sử dụng mô -đun lõi Node.js FS để có tất cả các tệp trong thư mục, chúng tôi có thể sử dụng các fsmethod sau.Node.js fs core module to get all files in the directory, we can use following
fsmethods.
- fs.readDir [đường dẫn, callbackFunction] - Phương thức này sẽ đọc tất cả các tệp trong thư mục. Bạn cần truyền đường dẫn thư mục làm đối số đầu tiên và trong đối số thứ hai, bạn có thể có bất kỳ chức năng gọi lại nào. — This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.
- path.join [] - Phương thức này của mô -đun đường dẫn Node.js, chúng tôi sẽ sử dụng để lấy đường dẫn của thư mục và điều này sẽ kết hợp tất cả các phân đoạn đường dẫn đã cho với nhau. — This method of node.js path module, we will be using to get the path of the directory and This will join all given path segments together.
Các bước để nhận danh sách tất cả các tệp trong một thư mục trong node.js
- Tải tất cả các gói NodeJS cần thiết bằng cách sử dụng các yêu cầu.“require”.
- Nhận đường dẫn của thư mục bằng phương thức path.join [].path.join[] method.
- Vượt qua chức năng đường dẫn thư mục và chức năng gọi lại trong phương thức fs.ReadDir [đường dẫn, callbackFunction].fs.readdir[path, callbackFunction] Method.
- Hàm gọi lại nên có xử lý lỗi và logic xử lý kết quả.
- Chức năng Callback xử lý lỗi và chạy foreach trên mảng danh sách các tệp từ thư mục.handle the error and run forEach on the array of files list from the directory.
- Áp dụng logic của bạn cho mỗi tệp hoặc tất cả các tệp bên trong hàm foreach.forEach function.
Mã đầy đủ:
lần đầu tiên xuất hiện trên blog phát triển web StackFrame.