skip to Main Content

I have some file names in "LATIN" but the fs.existsSync function is not able to recognise it

1689017335025-Naan En Nesarudaiyavan â mix.json

I tired with buffer too but still not able to get the proper response.

I am providing the proper path of the file too but still its not detecting that file.

I am using the fs module in electron js.

Other files other than Latin are been properly detected by fs.existsSync

const localDownloadPath = path.join(app.getPath('userData'), ${endpath}/${detail.name});
if(fs.existsSync(localDownloadPath)){ 
   return true; 
}else {return false;}

2

Answers


  1. As said in Node.js docs,

    Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile() is not recommended. Doing so introduces a rare condition, since other processes may change the file’s state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.

    So if you want to read/open a file, rather call the function and catch errors.

    Example of fs.readFile():

    const fs = require('node:fs');
    
    let fd;
    
    fs.readFile('myFile.txt','r',(err, data) => {
      if(err) {
        if(err.code == 'ENOENT') {
          console.error('myFile.txt does not exist');
          return;
        }
        throw err;
      }
      fd = data;
    });
    

    PS:
    I tried what you described in question as not working for you and it works well for me. Check if you wrote that filename correctly.
    Screenshot

    Login or Signup to reply.
  2. It might be an encoding issue. The fs.existsSync() function may not recognize file names containing non-ASCII characters or characters outside the standard character set.

    To ensure proper recognition of file names with non-ASCII characters, you can try using the fs.readdirSync() function instead.

    e.g.

    const localDownloadPath = path.join(app.getPath('userData'), endpath);
    
    const files = fs.readdirSync(localDownloadPath);
    const fileExists = files.includes(detail.name);
    
    if (fileExists) {
      // File exists
      return true;
    } else {
      // File does not exist
      return false;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search