简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM