How to use the readdirSync function from fs

Find comprehensive JavaScript fs.readdirSync code examples handpicked from public code repositorys.

fs.readdirSync is a function in the Node.js fs module that returns an array of all the filenames in a specified directory.

161
162
163
164
165
166
167
168
169
170
}
})
} // Credits By Hyzer Official, Don't Delete this
global.plugins = {} 
let pluginFolder = path.join(__dirname, "./plugins")
let fitur = fs.readdirSync(pluginFolder)
fitur.forEach(async (res) => {
const hijer = fs.readdirSync(`${pluginFolder}/${res}`).filter((file) => file.endsWith(".js"))
for (let filename of hijer ) {
try {
fork icon439
star icon57
watch icon2

+ 31 other calls in file

72
73
74
75
76
77
78
79
80
81

withVersions('jest', ['jest-environment-node', 'jest-environment-jsdom'], (version, moduleName) => {
  afterEach(() => {
    delete process.env.DD_API_KEY
    delete process.env.DD_APP_KEY
    const jestTestFile = fs.readdirSync(__dirname).filter(name => name.startsWith('jest-'))
    jestTestFile.forEach((testFile) => {
      delete require.cache[require.resolve(path.join(__dirname, testFile))]
    })
    delete require.cache[require.resolve(path.join(__dirname, 'env.js'))]
fork icon241
star icon444
watch icon463

How does fs.readdirSync work?

fs.readdirSync works by synchronously reading the contents of a specified directory and returning an array of all the filenames in that directory.

The function takes a single argument: the path to the directory to read.

It then reads the contents of the directory using the readdirSync function from the Node.js fs module.

The function returns an array of filenames in the directory, excluding subdirectories and their contents.

By using fs.readdirSync, developers can easily retrieve a list of filenames in a directory, which can be useful for tasks such as processing files or iterating over directories. However, it should be noted that because the function is synchronous, it can potentially block the Node.js event loop and make the application unresponsive if used with very large directories.

956
957
958
959
960
961
962
963
964
965
    novelai_settings.push(file2);
    novelai_setting_names.push(item.replace(/\.[^/.]+$/, ''));
});

//Styles
const designs = fs.readdirSync('public/designs')
    .filter(file => file.endsWith('.css'))
    .sort();

response.send({
fork icon60
star icon276
watch icon17

+ 3 other calls in file

294
295
296
297
298
299
300
301
302
303

_housekeepingSync: function (outputFileFolderWithoutSlash, outputFileName) {
  const tempFilePath = `${tempDir}/${outputFileName}`;
  if (fs.existsSync(tempFilePath)) {
    fs.renameSync(tempFilePath, `${outputFileFolderWithoutSlash}/${outputFileName}`);
    fs.readdirSync(outputFileFolderWithoutSlash).forEach((foundFile) => {
      if (foundFile !== outputFileName) {
        fs.unlinkSync(`${outputFileFolderWithoutSlash}/${foundFile}`);
      }
    });
fork icon50
star icon156
watch icon10

+ 12 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const fs = require("fs");

const directoryPath = "./myFolder";

try {
  const files = fs.readdirSync(directoryPath);
  console.log("Files in directory:");
  console.log(files);
} catch (err) {
  console.error(err);
}

In this example, we use fs.readdirSync to list all files in the directory ./myFolder. We first import the fs module. We define a variable directoryPath that contains the path to the directory we want to list. We then use fs.readdirSync to read the contents of the directory synchronously and store the filenames in an array called files. We log a message to the console indicating that we are listing the files, and then log the contents of the files array to the console. If an error occurs while attempting to read the directory, we catch the error and log it to the console. By using fs.readdirSync, we can easily list the filenames in a directory in our Node.js applications, which can be useful for tasks such as processing files or iterating over directories.

85
86
87
88
89
90
91
92
93
94
        if (entry.name === 'static' || entry.name === 'pyodide') {
            fs.rmSync(destFilePath, {recursive: true});
        }
    }
}
const entries = fs.readdirSync(src);
entries.sort();  // Fails if we hit index.html before _includes.
for (entry of entries) {
    let srcFilePath = path.join(src, entry),
        destFilePath = path.join(dest, entry);
fork icon54
star icon268
watch icon0

25
26
27
28
29
30
31
32
33
34
35
  throw new Error(`Missing or invalid crx file/directory, file: '${commander.crxFile} directory: '${commander.crxDirectory}'`)
}


const uploadJobs = []
if (fs.lstatSync(crxParam).isDirectory()) {
  fs.readdirSync(crxParam).forEach(file => {
    if (path.parse(file).ext === '.crx') {
      uploadJobs.push(util.uploadCRXFile(commander.endpoint, commander.region, path.join(crxParam, file)))
    }
  })
fork icon26
star icon31
watch icon30

+ 3 other calls in file

70
71
72
73
74
75
76
77
78
79
exports.open = co.promisify(fs.open);
exports.openSync = fs.openSync;
exports.read = co.promisify(fs.read);
exports.readSync = fs.readSync;
exports.readdir = co.promisify(fs.readdir);
exports.readdirSync = fs.readdirSync;
exports.readFile = co.promisify(fs.readFile);
exports.readFileSync = fs.readFileSync;
exports.readlink = co.promisify(fs.readlink);
exports.readlinkSync = fs.readlinkSync;
fork icon22
star icon45
watch icon26

18
19
20
21
22
23
24
25
26
27
28
29
30
}


function getNewContributors() {
  let newContributors = new Set()


  fs.readdirSync("./data/github").forEach((file) => {
    newContributors.add(file.split(".")[0])
  })


  fs.readdirSync("./contributors").forEach((file) => {
fork icon15
star icon7
watch icon7

+ 3 other calls in file

162
163
164
165
166
167
168
169
170
171
}

let pluginFolder = path.join(__dirname, 'plugins')
let pluginFilter = filename => /\.js$/.test(filename)
global.plugins = {}
for (let filename of fs.readdirSync(pluginFolder).filter(pluginFilter)) {
  try {
    global.plugins[filename] = require(path.join(pluginFolder, filename))
  } catch (e) {
    conn.logger.error(e)
fork icon13
star icon2
watch icon1

+ 3 other calls in file

43
44
45
46
47
48
49
50
51
52
53
54
}


function getFiles(dir) {
  let files = []


  const dirents = readdirSync(dir, { withFileTypes: true })
  for (const dirent of dirents) {
    const res = resolve(dir, dirent.name)
    if (dirent.isDirectory()) {
      files = files.concat(getFiles(res))
fork icon7
star icon40
watch icon0

29
30
31
32
33
34
35
36
37
38
39
40
41
let userTimeouts = new Map()


const mailSender = new MailSender(userGuilds, serverStatsAPI)


bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./src/commands').filter(file => file.endsWith('.js'));
const commands = []


for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
fork icon18
star icon33
watch icon0

107
108
109
110
111
112
113
114
115
116
// util.log(localdir);
var statzdir = fs.statSync(localdir);
if (! statzdir.isDirectory()) {
    throw "NOT A DIRECTORY " + localdir;
} else {
    var filez = fs.readdirSync(localdir);
    async.forEachSeries(filez,
        function(file, cb) {
            var localfile = path.normalize(path.join(localdir, file));
            // util.log('TEST ' + localfile +' PATH '+ path_local +' REMOTE '+ path_remote +' FILE '+ file);
fork icon7
star icon11
watch icon0

79
80
81
82
83
84
85
86
87
88
89
  recPath = ''
) {
  if (baseURL !== '' && !baseURL.endsWith('/')) {
    throw new Error("Non-empty baseURL must end with '/'.");
  }
  const files = fs.readdirSync(dir);
  files.sort(); // Sort entries for reproducibility.


  for (const fileName of files) {
    const filePath = path.join(dir, fileName);
fork icon6
star icon52
watch icon7

37
38
39
40
41
42
43
44
45
46
  } catch (e) {
   console.log(e);
  }
});

fs.readdirSync('./database/').forEach(db => {
 if (path.extname(db).toLowerCase() == '.js') {
  require('./database/' + db);
 }
});
fork icon3
star icon11
watch icon1

+ 23 other calls in file

111
112
113
114
115
116
117
118
119
120
if (opts['server']) require('./server')(global.conn, PORT)
if (opts['big-qr'] || opts['server']) conn.on('qr', qr => generate(qr, { small: false }))
function clearTmp() {
  const tmp = [os.tmpdir(), path.join(__dirname, './tmp')]
  const filename = []
  tmp.forEach(dirname => fs.readdirSync(dirname).forEach(file => filename.push(path.join(dirname, file))))
  filename.map(file => (
    stats = fs.statSync(file),
    stats.isFile() && (Date.now() - stats.mtimeMs >= 1000 * 60 * 3) ?
      fs.unlinkSync(file) :
fork icon92
star icon4
watch icon1

+ 3 other calls in file

203
204
205
206
207
208
209
210
211
212
exports.rmdir = function (dir) {
    if (!this.exist(dir)) {
        return;
    }
    // remove file first
    var files = fs.readdirSync(dir);
    if (!!files && files.length > 0) {
        files.forEach(function (v) {
            var file = dir + v;
            if (!this.isdir(file)) {
fork icon4
star icon25
watch icon3

158
159
160
161
162
163
164
165
166
167
 */
async function recursiveSearchAtPath(searchPath) {
	// try and catch to take care of illegal folders/files
	try {
		const ret = [];
		const dirs = fs.readdirSync(
			searchPath,
			{withFileTypes: true},
		).filter((d) => d.isDirectory()).map((d) => d.name);

fork icon0
star icon6
watch icon0

639
640
641
642
643
644
645
646
647
648
if (!fs.existsSync(plugin.components)) {
    logger.error('fail to find components, find path', { components: plugin.components })
    return
}

fs.readdirSync(plugin.components).forEach(function (filename) {
    if (!/\.js$/.test(filename)) {
        return
    }
    var name = path.basename(filename, '.js')
fork icon1
star icon3
watch icon1

175
176
177
178
179
180
181
182
183
184
        }
    }
    break
case 'notes':
    if (!fs.existsSync(`notes/${senderid}`)) fs.mkdirSync(`notes/${senderid}`)
    var folder = fs.readdirSync(`notes/${senderid}/`);
    fs.appendFile(`temp/${senderid}-notes.txt`, `${folder}`, err => {
        if (err) throw err;
    });
    fs.readFile(`temp/${senderid}-notes.txt`, 'utf8', function(err, data) {
fork icon1
star icon3
watch icon0

182
183
184
185
186
187
188
189
190
191
192
193
194
195
//#endregion




//#region set up bot commands


// const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); // Obsolete?


bot.commands = new Discord.Collection();
const forbiddenFolders = ['db', 'dev only']; //premium, 

fork icon0
star icon3
watch icon1