您好,欢迎访问一九零五行业门户网

node.js中的fs.realpathSync方法使用说明_node.js

方法说明:
同步版的 fs.realpath() 。
语法:
复制代码 代码如下:
fs.realpathsync(path, [cache])
由于该方法属于fs模块,使用前需要引入fs模块(var fs= require(“fs”) )
接收参数:
path                             路径
cache                           可选,一个文字的映射路径可用于强制一个特定的路径解决或避免额外的fs.stat需要知道真正的路径对象。
例子:
复制代码 代码如下:
var fs = require('fs');
// 点号表示当前文件所在路径
var str = fs.realpathsync('.');
console.log(str);
源码:
复制代码 代码如下:
fs.realpathsync = function realpathsync(p, cache) {
  // make p is absolute
  p = pathmodule.resolve(p);
  if (cache && object.prototype.hasownproperty.call(cache, p)) {
    return cache[p];
  }
  var original = p,
      seenlinks = {},
      knownhard = {};
  // current character position in p
  var pos;
  // the partial path so far, including a trailing slash if any
  var current;
  // the partial path without a trailing slash (except when pointing at a root)
  var base;
  // the partial path scanned in the previous round, with slash
  var previous;
  start();
  function start() {
    // skip over roots
    var m = splitrootre.exec(p);
    pos = m[0].length;
    current = m[0];
    base = m[0];
    previous = '';
    // on windows, check that the root exists. on unix there is no need.
    if (iswindows && !knownhard[base]) {
      fs.lstatsync(base);
      knownhard[base] = true;
    }
  }
  // walk down the path, swapping out linked pathparts for their real
  // values
  // nb: p.length changes.
  while (pos     // find the next part
    nextpartre.lastindex = pos;
    var result = nextpartre.exec(p);
    previous = current;
    current += result[0];
    base = previous + result[1];
    pos = nextpartre.lastindex;
    // continue if not a symlink
    if (knownhard[base] || (cache && cache[base] === base)) {
      continue;
    }
    var resolvedlink;
    if (cache && object.prototype.hasownproperty.call(cache, base)) {
      // some known symbolic link. no need to stat again.
      resolvedlink = cache[base];
    } else {
      var stat = fs.lstatsync(base);
      if (!stat.issymboliclink()) {
        knownhard[base] = true;
        if (cache) cache[base] = base;
        continue;
      }
      // read the link if it wasn't read before
      // dev/ino always return 0 on windows, so skip the check.
      var linktarget = null;
      if (!iswindows) {
        var id = stat.dev.tostring(32) + ':' + stat.ino.tostring(32);
        if (seenlinks.hasownproperty(id)) {
          linktarget = seenlinks[id];
        }
      }
      if (util.isnull(linktarget)) {
        fs.statsync(base);
        linktarget = fs.readlinksync(base);
      }
      resolvedlink = pathmodule.resolve(previous, linktarget);
      // track this, if given a cache.
      if (cache) cache[base] = resolvedlink;
      if (!iswindows) seenlinks[id] = linktarget;
    }
    // resolve the link, then start over
    p = pathmodule.resolve(resolvedlink, p.slice(pos));
    start();
  }
  if (cache) cache[original] = p;
  return p;
};
其它类似信息

推荐信息