Search code examples
javascriptnode.jsfilesystemshardlink

Detecting Hard Links in Node.js


How can I tell if a file-system path is a hard link with Node.js? The function fs.lstat gives a stats object that, when given a hard link will return true for stats.isDirectory() and stats.isFile() respectively. fs.lstat doesn't offer up anything to note the difference between a normal file or directory and a linked one.

If my understanding of how linking (ln) works is correct, then a linked file points to the same place on the disk as the original file. This would mean that both the original and linked version are identical, and there is no way to tell the difference between the original file and the linked.

The functionality I'm looking for is as follows:

This is hypothetical pseudo-code for demonstration & communication purposes.

fs.writeFileSync('./file.txt', 'hello world')
fs.linkSync('./file.txt', './link.txt')
fs.isLinkSync('./file.txt') // => false
fs.isLinkSync('./link.txt') // => true
fs.linkChildrenSync('./file.txt') // => ['./link.txt']
fs.linkChildrenSync('./link.txt') // => []
fs.linkParentSync('./link.txt') // => './file.txt'
fs.linkParentSync('./file.txt') // => null

Solution

  • Alright.. just for fun... You may have an option for finding the files via inode in a certain directory.

    Once you grab the inode ID from the stat object..

    fs.stat('./okay.file', function(err, stats){
      var inodeID = stats.ino; // Double check that this is correct
    });
    

    You can then iterate over all the files in the folder and check with a conditional if the inode ID matches. Get all files in a directory. If it doesn't, you can assume there is no link (IN that current directory).

    However, it doesn't look like we could search for a file by the inode id. see: nodejs open nfs files by inode (or a the fastest way to reopen a file)

    fs.lstat: https://nodejs.org/api/fs.html#fs_fs_lstat_path_callback

    Stats object: https://nodejs.org/api/fs.html#fs_class_fs_stats