3

I have this script:

var glob = require('glob');
glob('*.jpg', { cwd: 'public/portfolio/weddings/', sort: true }, function (err, files) {
  var globResults = files;
  globResults.forEach(function(entry) {
    var results = '\'' + entry + '\'';
    console.log(results.join(','));
  });
})

join(',') not work, causing the script to fail. Actual output without it:

'image-1.jpg'
'image-10.jpg'
'image-11.jpg'
'image-12.jpg'
'image-13.jpg'
'image-14.jpg'
'image-15.jpg'
'image-16.jpg'
'image-17.jpg'
'image-18.jpg'
'image-19.jpg'

Expected output:

'image-1.jpg',
'image-10.jpg',
'image-11.jpg',
'image-12.jpg',
'image-13.jpg',
'image-14.jpg',
'image-15.jpg',
'image-16.jpg',
'image-17.jpg',
'image-18.jpg',
'image-19.jpg'

Later on I want to call this output in a loop of array.

Lanti
  • 2,299
  • 2
  • 36
  • 69

1 Answers1

4
var glob = require('glob');
glob('*.jpg', { cwd: 'public/portfolio/weddings/', sort: true }, function (err, files) {
  var globResults = files,
      results = [];
  globResults.forEach(function(entry) {
    results.push('\'' + entry + '\'');
  });
  console.log(results.join(','));
})

Is this what you were looking for? The log should not be affected because of the callback of forEach because it's a blocking looping structure IIRC. If it does cause trouble you might have to use a regular for loop there.

On second thoughts why can't you just join the files directly? like this

console.log("'"+files.join("', '")+"'");
Achshar
  • 5,153
  • 8
  • 40
  • 70
  • Thank You! Works perfectly! I choosed your last method, joining them directly. I tried at the first try joining them directly, but probably I messed up something and it didn't worked, then I implemented forEach. But as you said, this is much simple solution. – Lanti Feb 08 '16 at 21:28