why else statement runs even if the if statement being true?

Guys, why the else statement runs even if the if statement is true
// file manager in node js --- FIRST PROJECT

const fs = require('fs'); //file system module
const path = require('path');

// First - specyfing the files extensions....
const images = ['.png', '.jpg', '.jpeg'];
const document = ['pdf', 'docx', 'doc'];
const videos = ['mp4', 'mov'];

//Read files from the source directory (folder named 'source')

//readdir - get list of every file inside the folder...
fs.readdir('./source', (err, files) => {
if (err) {
console.log(err);
} else {
files.forEach((file) => {
const filesExtention = path.extname(file).toLowerCase(); //path.extname allow you to extract specific components from file paths, such as file extensions.
if (filesExtention === images[1]) {
console.log('there is a .jpg file');
} else {
console.log('nothing here!');
}
});
}
});
// file manager in node js --- FIRST PROJECT

const fs = require('fs'); //file system module
const path = require('path');

// First - specyfing the files extensions....
const images = ['.png', '.jpg', '.jpeg'];
const document = ['pdf', 'docx', 'doc'];
const videos = ['mp4', 'mov'];

//Read files from the source directory (folder named 'source')

//readdir - get list of every file inside the folder...
fs.readdir('./source', (err, files) => {
if (err) {
console.log(err);
} else {
files.forEach((file) => {
const filesExtention = path.extname(file).toLowerCase(); //path.extname allow you to extract specific components from file paths, such as file extensions.
if (filesExtention === images[1]) {
console.log('there is a .jpg file');
} else {
console.log('nothing here!');
}
});
}
});
i'd rather have something like this, but all you're missing is the type definition of connection there
No description
7 Replies
ErickO
ErickO•17mo ago
why the else statement runs even if the if statement is true
there's 99.999999% chance the if statement is, in fact, not true and therefore the else statement runs there's 0.000001% chance the Javascript is wrong and you're right you also don't say uh...which if statement you're having trouble with, there's 2 of them
Sste
Sste•17mo ago
the one that checks if has a .jpg file in the folder what can I do to solve it? I am getting this message in the terminal
Sste
Sste•17mo ago
No description
ErickO
ErickO•17mo ago
probably means that is running 2 times, one time it has a .jpg file and the 2nd time it has a file that is not a jpg I'd start by checking if you are getting what you expect, console.log the name of the file or even just the extension, you'll see it running twice
Sste
Sste•17mo ago
if I just wanna check one file?
ErickO
ErickO•17mo ago
either make sure there's only one file in your directory or don't use a loop to go through all the files, just pick the first one
Sste
Sste•17mo ago
okay, thanks 🙂
Want results from more Discord servers?
Add your server