简体   繁体   中英

Symbolic-Link always points to its parent directory

Placing Symbolic-Links other than the current directory does not work because they always point to their current directory

I'm on Windows 10, what I'm missing?

fs.symlink('./testFile', './testDir/testSymLink', function(err){       // creates a symbolic- link in the 'testDir' subfolder relative to the current directory 
    if(err) console.log(err);
});

fs.readlink('./testDir/testSymlink',function(err, links){              // reads the created symbolic link 
    if(err) console.log(err);
    console.log(links);                                                // -> '.\testFile'   (points to the current directory not to the parent directory)
});

fs.readFile('./testDir/testSymlink.txt', function(err, data){          // file doesn't exist
    if(err) console.log(err);                                          // -> ENOENT no such file or directory 
    console.log(data);                                                 // -> undefined 
});

The symbolic link is created (we can read it) but points to its current directory .\testFile it should point to its parent directory where the reference file is ..\testFile

the symlink() method's 1st argument is the target location used by the created symbolic-link.

It's is important to know that the symbolic-link uses the 1st argument as it was passed! (does not resolve it as absolute path!)

Here is the tricky part, because the above 1st argument is ./testFile the symbolic-link will use this path to reference the 'testFile' in its own directory (not in the parent directory)

Solutions:

1: the above code could be fixed like this (the testSymLink in the testDir directory references the testFile in the parent directory)

fs.symlink('../testFile', './testDir/testSymLink', function(err){       
    if(err) console.log(err);
});

2: passing absolute path as 1st argument in the symlink() method (this will save you a lot of hassle!)

fs.symlink(/* absolute path */, './testDir/testSymLink', function(err){       
    if(err) console.log(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM