Detecting Hard Links in Node.js
Asked Answered
K

2

7

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
Kalgan answered 5/8, 2015 at 4:8 Comment(0)
S
5

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

Subdeacon answered 5/8, 2015 at 6:50 Comment(0)
M
0

Sorry but that is not possible you can't differ between original and hard linked file. They are the same on your linux system and poinzing to the same inode.

Mabe answered 5/8, 2015 at 4:19 Comment(1)
This provides a little more information on the topic: unix.stackexchange.com/questions/122333/…Subdeacon

© 2022 - 2024 — McMap. All rights reserved.