find the path of a file in javascript

In browser environments, you can use the File API to get the path of a file. However, it is only available when the user explicitly selects the file using an input element in the HTML page. This is due to security reasons - web pages should not have access to the file system without the user's consent.

index.tsx
let fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.addEventListener('change', function(event) {
  console.log(event.target.files[0].path);
});
fileInput.click();
195 chars
7 lines

In a Node.js environment, you can use the built-in path module to get the path of a file.

index.tsx
const path = require('path');

// absolute path
console.log(path.resolve('/etc', 'nginx', 'nginx.conf')); // /etc/nginx/nginx.conf

// relative path
console.log(path.resolve('index.html')); // /Users/username/projects/myapp/index.html
235 chars
8 lines

Note that in Node.js, you can only access files within the scope of your application. You cannot access arbitrary files on the file system without explicit permissions.

gistlibby LogSnag