There is a local server:

const express = require('express'), server = express(), files = [ 'Collapse.mp3', 'Eidolon.mp3' ]; server.listen(8080); server.use(express.static('dist')); server.get('/', function(request, response) { response.send(__dirname + '/dist/index.html'); response.end(); }); for (var i = 0; i < files.length; i++) { server.get('/dist/downloads/' + files[i], function(request, response) { response.download(__dirname + '/dist/downloads/' + files[i]); }); } 

But I do not understand why the last cycle for loading two files does not work. Displayed using console.log, the paths are correct, but when you try to download it writes: Error: ENOENT: no such file or directory, stat 'D: \ Documents \ 3-2_web_file_server \ dist \ downloads \ undefined'.

With this format, everything works:

 server.get('/dist/downloads/Collapse.mp3', function(request, response) { response.download(__dirname + '/dist/downloads/Collapse.mp3'); }); server.get('/dist/downloads/Eidolon.mp3', function(request, response) { response.download(__dirname + '/dist/downloads/Eidolon.mp3'); }); 

But I don’t want to do this this way because there may be more files and I don’t want to write a separate request for each one. Please tell me what the problem is and how to implement it correctly. Thank.

  • one
    Write let instead var - Alexey Ten
  • @AlexeyTen Thanks, works! - undefined

1 answer 1

What is the matter: the transferred function is called after the cycle has completed and the value of the variable i has been set to 2 permanently. At this index there is no value in the array.

 var files = ['Collapse.mp3', 'Eidolon.mp3']; for( var i = 0; i < files.length; ++i ) { doSthWithCallbacks(`a-${files[i]}-b`, function() { console.log(i, files[i]); }); } function doSthWithCallbacks(str, cb) { console.log(`str=${str}`); setTimeout(cb, 200); } 

How to get around this - use let to declare a variable i or:

 var files = ['Collapse.mp3', 'Eidolon.mp3']; files.forEach((file) => { doSthWithCallbacks(`a-${file}-b`, function() { console.log(file); }); }); function doSthWithCallbacks(str, cb) { console.log(`str=${str}`); setTimeout(cb, 200); } 

  • Thank you very much! It helped. - undefined