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
If you find two files with identical properties but are unsure if they are hard-linked, use the ls -i command to view the inode number. Files that are hard-linked together share the same inode number. The shared inode number is 2730074, meaning these files are identical data.
The real test is to use the ls -li command. This command will show the inode for each of the two files. If the inodes match, then the files really are hard links, sharing disk space and the inode structure which houses their metadata (owner, permissions, etc.).
The hard link count is stored in the inode. It starts at 1 when the file is created, increases by 1 each time the link system call is successful, and decreases by 1 each time the unlink system call is successful.
Although some refer to soft links as pointers or shortcuts, experts point out that both hard links and soft links are technically pointers, but that hard links are more persistent pointers.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With