Checking if a file exists?

Discussion in 'Server and Client Scripting' started by Garma, May 2, 2013.

  1. Garma

    Garma Member

    Joined:
    Nov 23, 2011
    Messages:
    80
    Likes Received:
    0
    Is there a way to check if a file exists? I know something like [ -f xxxx.json ] && echo true || echo false ] but I dont know if I can execute that server-side, sys.system() doens't really work. :x
     
  2. TheUnknownOne

    TheUnknownOne Member

    Joined:
    Mar 28, 2011
    Messages:
    988
    Likes Received:
    3
    Code (text):
    1.  
    2. !!sys.getFileContent(name)
    3.  
    or
    Code (text):
    1.  
    2. sys.appendToFile(name, '');
    3. if (sys.getFileContent(name) === '') {
    4. // false
    5. sys.deleteFile(name);
    6. } else {
    7. // true
    8. }
    9.  
    Note that the second example considers empty files to be non-existent as well. However, it does not trigger script warnings if the file doesn't exist.
     
  3. Garma

    Garma Member

    Joined:
    Nov 23, 2011
    Messages:
    80
    Likes Received:
    0
    Ok, thanks. !!sys.getFileContent() works. But for some explanation.. I have never seen two exclamation marks in a row before a statement/function. What does that exactly do?
     
  4. Lamperi

    Lamperi I see what you did there

    Joined:
    Apr 25, 2010
    Messages:
    2,647
    Likes Received:
    11
    First one casts the value to boolean and inverts the value, second one inverts the value again. Basically, it's shortest syntax to cast an exprssion to boolean. But usually it is not required in Javascript, as expressions are casted to boolean anyway when relevant in if-clause or while-clause.