Lanti February 2016

Joining loop of arrays in Node.js glob results

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.

Answers


Achshar February 2016

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("', '")+"'");

Post Status

Asked in February 2016
Viewed 3,809 times
Voted 10
Answered 1 times

Search




Leave an answer