3

I am trying to figure out the proper syntax of how to write an if statement that checks if x == (at least one of many vars)

I have an example what what I am trying to get to...

var path = require('path')
var fs = require('fs')
var file1 = './frank.txt'
var file2 = './jasmine.html'
var file3 = './finnigan.jpg'

if (fs.statSync(file2).isFile && path.extname(file2) == ['.txt' || '.html']) {
  console.log('true')
} else {
  console.log('failure')
}

I know the syntax on the after is && is weird, but what is the correct syntax for the situation?

ms_nitrogen
  • 240
  • 1
  • 14
  • 1
    There are many ways. The first is `(path.extname(file2) == '.txt' || path.extname(file2) == '.html')` but that's bad for obvious reasons. `['.txt','.html'].indexOf(path.extname(file2)) > -1` works. As does `path.extname(file2).match(/\.(?:txt|html)$/)`... – Niet the Dark Absol Aug 02 '16 at 17:39
  • Check [this](http://stackoverflow.com/questions/25171143/how-do-i-use-the-includes-method-in-lodash-to-check-if-an-object-is-in-the-colle) it uses lodash module to facilitate this kind of work – n0m4d Aug 02 '16 at 17:41

3 Answers3

2

You can check if a certain index exists by the elment:

if (fs.statSync(file2).isFile && ['.txt', '.html'].indexOf(path.extname(file2)) > -1) {
  console.log('true');
} 
else {
  console.log('failure');
}
Davide Perozzi
  • 386
  • 2
  • 13
2

You can also use a regex like this

var path = require('path');
var fs = require('fs');
var file1 = './frank.txt';
var file2 = './jasmine.html';
var file3 = './finnigan.jpg';
var extRegex = new RegExp(/^(\.txt|\.html)$/);

if ( fs.statSync(file2).isFile && extRegex.test( path.extname(file2) ) ) {
  console.log('true');
} else {
  console.log('failure');
}
anthony
  • 126
  • 1
  • 4
0

If i am getting you correct then you can use Jquery inArray function in your case.

var arr=[ './frank.txt', './frank.html', './frank.jpg', './frank.csv' ] ;

if( $.inArray( 'file.exe',arr )!=-1)
{
     console.log('true');
}
else
{ 
     console.log('false');
}
Deepak
  • 1,510
  • 1
  • 14
  • 27