Javascript get files list

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

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 ‘..

You’ll get the list of all files the files in directory in your callback argument. You can filter that.

5 Answers 5

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.

to someone doing copy/paste this answer is missing the actual reading of the directory which would be the case on the answer of Lazyexpert

Читайте также:  Как поставить на фон картинку в HTML

Basically, you do something like this:

const path = require('path') const fs = require('fs') const dirpath = path.join(__dirname, '/path') fs.readdir(dirpath, function(err, files) < const txtFiles = files.filter(el =>path.extname(el) === '.txt') // do something with your files, by the way they are just filenames. >) 

I agree, in some complex cases its all true. But this one, seriously: /\.txt$/ , takes time to read and understand?

I wonder, how many time it took you to read and understand that regexp? How many ms? I repeat, in most cases — I totally agree. But the simpliest. what are we even talking about.

You can write 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 , that is 10. Everyone can add right? It has 0 complexity? But it is a waste of time for the reader. Just write 10 . Having to do that sum in your head distracts the reader from understanding how 10 fits into the rest of the code.

fs doesn’t support filtering itself but if you don’t want to filter youself then use glob

var glob = require('glob'); // options is optional glob("**/*.js", options, function (er, files) < // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. >) 

I used the following code and its working fine:

var fs = require('fs'); var path = require('path'); var dirPath = path.resolve(__dirname); // path to your directory goes here var filesList; fs.readdir(dirPath, function(err, files)< filesList = files.filter(function(e)< return path.extname(e).toLowerCase() === '.txt' >); console.log(filesList); >); 
const fs = require('fs'); const path = require('path'); // Path to the directory(folder) to look into const dirPath = path.resolve(`$../../../../../tests_output`); // Read all files with .txt extension in the specified folder above const filesList = fs.readdirSync(dirPath, (err, files) => files.filter((e) => path.extname(e).toLowerCase() === '.txt')); // Read the content of the first file with .txt extension in the folder const data = fs.readFileSync(path.resolve(`$../../../../../tests_output/$`), 'utf8'); 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Get list of filenames in folder with Javascript

My website is serving a lot of pictures from /assets/photos/ folder. How can I get a list of the files in that folder with Javascript?

What have you tried? And in what context do you want to retrieve the list of files. From the browser or from a server with node.js?

@Mike I doubt the browser choice really matters. The browser doesn’t have access to the list of files unless the server presents it.

13 Answers 13

The current code will give a list of all files in a folder, assuming it’s on the server side you want to list all files:

var fs = require('fs'); var files = fs.readdirSync('/assets/photos/'); 

Where does require() come from or is defined. Your code proiduces a «‘require’ is not defined» error. Have you tested your code? If so, have you maybe missed some important part referring to ‘require’?

@Apostolos As OP notes in the description, this needs to be server-side code. You can not run this in a browser. Running this script with Node.js does not throw any errors.

This is a good way but seems doesn’t answer the question directly. The simple answer is No, in JS from client side(browser) there is no direct way to get list of files in a folder/directory on server side.

No, Javascript doesn’t have access to the filesystem. Server side Javascript is a whole different story but I guess you don’t mean that.

@jtheletter The API is running on the server, so you’d use whatever stack you have running on your server. If that’s Node, it would be fs.readdir.

I write a file dir.php

var files = echo json_encode($out); ?>; 

@2540625 that is php, not pure javascript. Despite you need php and it does not solve the issue of the author, it is still a pretty good solution if you have php.

Alternatively if you want to list all files, either use *.* or use scandir to preserve file extensions, $out = scandir(«.»); echo json_encode($out);

For getting the list of filenames in a specified folder, you can use:

fs.readdir(directory_path, callback_function) 

This will return a list which you can parse by simple list indexing like file[0],file[1] , etc.

For client side files, you cannot get a list of files in a user’s local directory.

If the user has provided uploaded files, you can access them via their input element.

   

I made a different route for every file in a particular directory. Therefore, going to that path meant opening that file.

I called this function passing the list of filename in the directory __dirname/public/extracted and it created a different route for each filename which I was able to render on server side.

I use the following (stripped-down code) in Firefox 69.0 (on Ubuntu) to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from «outside».

var directory = ; var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', directory, false); // false for synchronous request xmlHttp.send(null); var ret = xmlHttp.responseText; var fileList = ret.split('\n'); for (i = 0; i < fileList.length; i++) < var fileinfo = fileList[i].split(' '); if (fileinfo[0] == '201:') < document.write(fileinfo[1] + "
"); document.write(''); > >

This requires the policy security.fileuri.strict_origin_policy to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.

Источник

FileList

All element nodes have a files attribute of type FileList on them which allows access to the items in this list. For example, if the HTML includes the following file input:

input id="fileItem" type="file" /> 

The following line of code fetches the first file in the node’s file list as a File object:

const file = document.getElementById("fileItem").files[0]; 

Note: This interface was an attempt to create an unmodifiable list and only continues to be supported to not break code that’s already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

Instance properties

A read-only value indicating the number of files in the list.

Instance methods

Returns a File object representing the file at the specified index in the file list.

Example

Logging filenames

In this example, we log the names of all the files selected by the user.

HTML

input id="myfiles" multiple type="file" /> pre class="output">Selected files:pre> 

CSS

.output  overflow: scroll; margin: 1rem 0; height: 200px; > 

JavaScript

const output = document.querySelector(".output"); const fileInput = document.querySelector("#myfiles"); fileInput.addEventListener("change", () =>  for (const file of fileInput.files)  output.innerText += `\n$file.name>`; > >); 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 24, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

best way to get folder and file list in Javascript

I’m using node-webkit, and am trying to have a user select a folder, and I’ll return the directory structure of that folder and recursively get its children. I’ve got this working fairly simply with this code (in an Angular Controller).

var fs = require('fs'); $scope.explorer=[]; $scope.openFile = function()< $scope.explorer = [tree_entry($scope.path)]; get_folder($scope.path, $scope.explorer[0].children); >; function get_folder(path, tree) < fs.readdir(path, function(err,files)< if (err) return console.log(err); files.forEach( function (file,idx)< tree.push(tree_entry(file)); fs.lstat(path+'/'+file,function(err,stats)< if(err) return console.log(err); if(stats.isDirectory())< get_folder(path+'/'+file,tree[idx].children); >>); >); >); console.log($scope.explorer); return; > function tree_entry(entry) < return < label : entry, children: []>> 

Taking a moderate sized folder with 22 child folders and about 4 levels deep, it is taking a few minutes to get the entire directory structure. Is there something that I’m obviously doing wrong here? I can’t believe it takes that long, seeing as I’m using the built in Node fs methods. Or is there a way to get the entire contents of a directory without touching each and every file? I’m going to want to be able to use an Angular filter on the file names all the way down the tree, and possibly on the contents too, so delaying processing the entire tree isn’t likely a solution that would work.

Perhaps it is getting .. as a file. You probably should put a few console.log’s around to learn a little more about what is happening.

You mean it is opening each file? No, that doesn’t seem to be the problem, I was about to delete the question, turns out if I removed the console.log and put in a callback which output to the console once, things happen much faster.

What you need is a simple recursive walking function that traverses a directory. Google is your friend.

4 Answers 4

In my project I use this function for getting huge amount of files. It’s pretty fast (put require(«fs») out to make it even faster):

var _getAllFilesFromFolder = function(dir) < var filesystem = require("fs"); var results = []; filesystem.readdirSync(dir).forEach(function(file) < file = dir+'/'+file; var stat = filesystem.statSync(file); if (stat && stat.isDirectory()) < results = results.concat(_getAllFilesFromFolder(file)) >else results.push(file); >); return results; >; 
_getAllFilesFromFolder(__dirname + "folder"); 

@GeekyInt you probably have a symlink in your directory structure pointing to a containing folder. In that case you can use fs.lstat() instead of fs.stat() .

For an efficient, non-blocking (async) technique using Node’s fast fs.Dirent objects, I added an answer to this thread.

fs/promises and fs.Dirent

Here’s an efficient, non-blocking ls program using Node’s fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist or fs.stat calls on every path —

// main.js import < readdir >from "fs/promises" import < join >from "path" async function* ls (path = ".") < yield path for (const dirent of await readdir(path, < withFileTypes: true >)) if (dirent.isDirectory()) yield* ls(join(path, dirent.name)) else yield join(path, dirent.name) > async function* empty () <> async function toArray (iter = empty()) < let r = [] for await (const x of iter) r.push(x) return r >toArray(ls(".")).then(console.log, console.error) 

Let’s get some sample files so we can see ls working —

$ yarn add immutable # (just some example package) $ node main.js 
[ '.', 'main.js', 'node_modules', 'node_modules/.yarn-integrity', 'node_modules/immutable', 'node_modules/immutable/LICENSE', 'node_modules/immutable/README.md', 'node_modules/immutable/contrib', 'node_modules/immutable/contrib/cursor', 'node_modules/immutable/contrib/cursor/README.md', 'node_modules/immutable/contrib/cursor/__tests__', 'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip', 'node_modules/immutable/contrib/cursor/index.d.ts', 'node_modules/immutable/contrib/cursor/index.js', 'node_modules/immutable/dist', 'node_modules/immutable/dist/immutable-nonambient.d.ts', 'node_modules/immutable/dist/immutable.d.ts', 'node_modules/immutable/dist/immutable.es.js', 'node_modules/immutable/dist/immutable.js', 'node_modules/immutable/dist/immutable.js.flow', 'node_modules/immutable/dist/immutable.min.js', 'node_modules/immutable/package.json', 'package.json', 'yarn.lock' ] 

For added explanation and other ways to leverage async generators, see this Q&A.

Источник

Оцените статью