سؤال

I have the following code for displaying file names in a given directory

var fs = require('fs');
fs.readdir('folder/', function (err, files) 
{
  if (err)
    throw err;
  for (var index in files)
    {
      console.log(files[index]);
    }
});

Here how can I store all the file names in an array after the completion of for loop condition.

هل كانت مفيدة؟

المحلول

You can create an array and use the push() method.

var fs = require('fs');
fs.readdir('.', function (err, files) {
  if (err) throw err;

  var filenames = [];
  for (var index in files) {
    console.log(files[index]);
    filenames.push(files[index]);
  }

  // do something with "filenames"
  // ['file1.js', 'file2.js', 'file3.js']
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top