Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node's fs.symlink() believes the link already exists; definitely doesn't

Tags:

node.js

fs

I have this code:

// ...

var symlinkPrecommit = function (callback) {

  console.log("\n > Creating pre-commit symlink in .git/hooks/pre-commit\n");

  source = path.resolve('.git/hooks/pre-commit');
  target = path.resolve('precommit.js');

  fs.symlink(source, target, 'file', function (err) {
    if (err) {
      console.log(
        err.code === 'EEXIST' ? "Link already created!\n" : "Error\n"
      );
      console.log(err);
    }
    if (callback) callback();
  });

}

// ...

When I run it, I get this:

MaffBookPro: matt$ ./build.js

 > Creating pre-commit symlink in .git/hooks/pre-commit

Link already created!

{ [Error: EEXIST, symlink '/Users/matt/work/project/.git/hooks/pre-commit']
  errno: 47,
  code: 'EEXIST',
  path: '/Users/matt/work/project/.git/hooks/pre-commit' }

But when I ls -lah the directory in which it's trying to create the symlink, the file definitely doesn't already exist- and the permissions look completely fine:

MaffBookPro: matt$ ls -lah .git/hooks/
total 80
drwxr-xr-x  11 matt  staff   374B  9 Nov 15:39 .
drwxr-xr-x  15 matt  staff   510B  9 Nov 15:45 ..
-rwxr-xr-x   1 matt  staff   452B  9 Oct 12:52 applypatch-msg.sample
-rwxr-xr-x   1 matt  staff   896B  9 Oct 12:52 commit-msg.sample
-rwxr-xr-x   1 matt  staff   189B  9 Oct 12:52 post-update.sample
-rwxr-xr-x   1 matt  staff   398B  9 Oct 12:52 pre-applypatch.sample
-rwxr-xr-x   1 matt  staff   1.6K  9 Oct 12:52 pre-commit.sample
-rwxr-xr-x   1 matt  staff   1.3K  9 Oct 12:52 pre-push.sample
-rwxr-xr-x   1 matt  staff   4.8K  9 Oct 12:52 pre-rebase.sample
-rwxr-xr-x   1 matt  staff   1.2K  9 Oct 12:52 prepare-commit-msg.sample
-rwxr-xr-x   1 matt  staff   3.5K  9 Oct 12:52 update.sample

Any ideas? Thanks in advance!

like image 637
Matt Fletcher Avatar asked Nov 09 '14 15:11

Matt Fletcher


1 Answers

This was counter-intuitive to me as I imagined src -> dst, but in : fs.symlink(srcpath, dstpath[, type], callback)

  • srcpath is what the link is pointing to
  • dstpath is where the new link will be created

It is named in the same way as the unix ln command, and its easier to remember if you don't think about the link being constructed but instead remember it has the same interface as cp, where the source is the existing file and the destination is where the new file will be created.

like image 160
MikeB Avatar answered Sep 19 '22 00:09

MikeB