Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - How do I get a list of files with specific file extension using node.js?

The node fs package has the following methods to list a directory:

fs.readdir(path, [callback]) Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

fs.readdirSync(path) Synchronous readdir(3). Returns an array of filenames excluding '.' and '..

But how do I get a list of files matching a file specification, for example *.txt?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could filter they array of files with an extension extractor function. The path module provides one such function, if you don't want to write your own string manipulation logic or regex.

const path = require('path');

const EXTENSION = '.txt';

const targetFiles = files.filter(file => {
    return path.extname(file).toLowerCase() === EXTENSION;
});

EDIT As per @arboreal84's suggestion, you may want to consider cases such as myfile.TXT, not too uncommon. I just tested it myself and path.extname does not do lowercasing for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...