How to use the lstatSync function from fs-extra

Find comprehensive JavaScript fs-extra.lstatSync code examples handpicked from public code repositorys.

The fs-extra.lstatSync method is similar to the fs.lstatSync method and returns information about a file, but it can also handle symbolic links.

165
166
167
168
169
170
171
172
173
174
```

You can also filter the results to only return the files, and exclude the folders:

```
const isFile = fileName => {  return fs.lstatSync(fileName).isFile()}
```

```
fs.readdirSync(folderPath).map(fileName => {  return path.join(folderPath, fileName)).filter(isFile)}
fork icon191
star icon1
watch icon0

+ 13 other calls in file

3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
    }
}

if (createdFiles.length > 0) {
    for (var createdFile of createdFiles) {
        if (fs.existsSync(createdFile) && fs.lstatSync(createdFile).isFile()) {   
            var createdFileData = fs.readFileSync(createdFile, { encoding: 'utf8' });

            if (createdFileData == '' || createdFileData == '<?xml version="1.0" encoding="UTF-8"?>') {
                fs.removeSync(createdFile);
fork icon82
star icon94
watch icon26

+ 7 other calls in file

How does fs-extra.lstatSync work?

The fs-extra.lstatSync() method is a synchronous version of the fs-extra.lstat() method, which returns the fs.Stats object for a file or directory. This method is used to get the metadata of a file or directory like its size, creation time, and modification time. The method takes a file path as input and returns a fs.Stats object that can be used to extract various file properties.

63
64
65
66
67
68
69
70
71
72
73
74
function get_require_path(req_path) {


    let rm = require.main.path;


    try {
        let stat = fs.lstatSync(rm);
        if (!stat.isDirectory()) {
            console.log(error_header);
            console.log("require.main.path is not a directory.");
            return;
fork icon6
star icon21
watch icon3

+ 9 other calls in file

47
48
49
50
51
52
53
54
55

```js

const isFile = fileName => {

  return fs.lstatSync(fileName).isFile()

}

fork icon2
star icon4
watch icon0

+ 11 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
const fs = require("fs-extra");

try {
  const stats = fs.lstatSync("/path/to/file");
  console.log(stats.isFile()); // true
  console.log(stats.isDirectory()); // false
} catch (err) {
  console.error(err);
}

In this example, fs.lstatSync is used to get information about the file located at /path/to/file. The returned stats object is then used to determine if the file is a regular file (stats.isFile()) or a directory (stats.isDirectory()). If there is an error, it is caught and logged to the console.

155
156
157
158
159
160
161
162
163
164

Можно также отфильтровать результаты, чтобы вернуть только файлы и исключить папки:

```js
const isFile = (fileName) => {
    return fs.lstatSync(fileName).isFile();
};

fs.readdirSync(folderPath)
    .map((fileName) => {
fork icon14
star icon101
watch icon3

+ 11 other calls in file

105
106
107
108
109
110
111
112
113
114
fns.sort().filter(function (fn) {
  var fullPath = fspath.join(path, fn);
  // we use fs.realpathSync to also resolve Symbolic Link
  var absoluteFullPath = fs.realpathSync(fspath.join(root, fullPath));
  if (fn[0] != ".") {
    var stats = fs.lstatSync(absoluteFullPath);
    if (stats.isDirectory()) {
      dirs.push(fn);
    } else {
      var meta = getFileMeta(root, fullPath);
fork icon0
star icon2
watch icon0

7064
7065
7066
7067
7068
7069
7070
7071
7072
if (options.preserveTimestamps && process.arch === 'ia32') {
  console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
  see https://github.com/jprichardson/node-fs-extra/issues/269`)
}

const stats = (options.recursive && !options.dereference) ? fs.lstatSync(src) : fs.statSync(src)
const destFolder = path.dirname(dest)
const destFolderExists = fs.existsSync(destFolder)
let performCopy = false
fork icon0
star icon1
watch icon0

+ 26 other calls in file

280
281
282
283
284
285
286
287
288
289
if (productionPackages.indexOf(src) == -1) {
    // Not a production dependency, skip it.
    return;
}

const stat = fse.lstatSync(src);
if (stat.isSymbolicLink()) {
    // This is a link to another package, presumably created by Lerna.
    fse.ensureDirSync(dest);
    preparePackage(src, dest);
fork icon1
star icon0
watch icon0

16
17
18
19
20
21
22
23
24
25
if (!isApiPathExist) {
  // NAS 文件存在,加载软链
  fs.ensureSymlinkSync(nasPath, apiPath);
} else {
  // 如果src/api 路径存在
  const fd = fs.lstatSync(apiPath);

  // 如果已经存在src/api 文件夹,需要删除掉。
  // TODO: 是否这个能力通过开关控制
  if (fd.isDirectory()) {
fork icon0
star icon2
watch icon0

106
107
108
109
110
111
112
113
114
115
  });
  return filelist;
};

function setMetadata(path, data, recursive) {
  var stats = fs.lstatSync(path);
  var realpath = path, followSymlink = false;
  if (stats.isSymbolicLink()) {
    // We need to operate on its target, so resolve the symlink
    var target = fs.readlinkSync(path);
fork icon0
star icon1
watch icon2

+ 3 other calls in file

375
376
377
378
379
380
381
382
383
384
  `The directory ${chalk.green(name)} contains files that could conflict:`
);
console.log();
for (const file of conflicts) {
  try {
    const stats = fs.lstatSync(path.join(root, file));
    if (stats.isDirectory()) {
      console.log(`  ${chalk.blue(`${file}/`)}`);
    } else {
      console.log(`  ${file}`);
fork icon109
star icon608
watch icon8

+ 4 other calls in file

16
17
18
19
20
21
22
23
24
25
const targetRoot = path.join(dotaPath, directoryName, "dota_addons");
assert(fs.existsSync(targetRoot), `Could not find '${targetRoot}'`);

const targetPath = path.join(dotaPath, directoryName, "dota_addons", getAddonName());
if (fs.existsSync(targetPath)) {
    const isCorrect = fs.lstatSync(sourcePath).isSymbolicLink() && fs.realpathSync(sourcePath) === targetPath;
    if (isCorrect) {
        console.log(`Skipping '${sourcePath}' since it is already linked`);
        continue;
    } else {
fork icon1
star icon0
watch icon1

+ 9 other calls in file

1508
1509
1510
1511
1512
1513
1514
1515
1516
if (entry.startsWith(".")) {
    return false;
}

let sclPath = path.join(config.stdcellRepo, entry);
let stat = fs.lstatSync(sclPath);
if (!stat.isDirectory()) {
    return false;
}
fork icon0
star icon2
watch icon3

+ 19 other calls in file

1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
    "models.v"
);
const stdCellDest = `${sourcePath}/${stdcell}.v`;
try {
    const stat =
        fs.lstatSync(stdcellPath);
} catch (e) {
    console.error(e);
    return cb({
        error: `Cannot find the standard cell models for this library ${stdcell}`,
fork icon0
star icon2
watch icon3

+ 9 other calls in file

1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
if (mark === 0 && models.length === 0) {
    const cwd = process.cwd();
    const defaultGLTFPath = path.join(cwd, 'model.gltf');
    const defaultGLBPath = path.join(cwd, 'model.glb');

    if (fs.existsSync(defaultGLTFPath) && fs.lstatSync(defaultGLTFPath).isFile()) {
        addInputModel(models, defaultGLTFPath, defaultSimplificationRatio);
    } else if (fs.existsSync(defaultGLBPath) && fs.lstatSync(defaultGLBPath).isFile()) {
        addInputModel(models, defaultGLBPath, defaultSimplificationRatio);
    } else {
fork icon0
star icon0
watch icon1

+ 59 other calls in file

995
996
997
998
999
1000
1001
1002
1003
1004
fns.sort(function(A,B) {
    return A.toLowerCase().localeCompare(B.toLowerCase());
}).filter(function(fn) {
    var fullPath = fspath.join(projectsDir,fn);
    if (fn[0] != ".") {
        var stats = fs.lstatSync(fullPath);
        if (stats.isDirectory()) {
            dirs.push(fn);
        }
    }
fork icon0
star icon0
watch icon1

75
76
77
78
79
80
81
82
83
84
 * @param {*} https 
 */
function validateCerts(https) {
    Object.keys(https).forEach(prop => {
        try {
            fs.lstatSync(https[prop]);
        } catch (err) {
            jeliUtils.console.write(jeliUtils.colors.red(`Error: Could not find ${prop} -> ${https[prop]}`));
            process.exit(1);
        }
fork icon0
star icon0
watch icon2

+ 12 other calls in file

36
37
38
39
40
41
42
43
44
45
const res = [];
const files = fs.readdirSync(dir);
// eslint-disable-next-line no-plusplus
for (let index = 0; index < files.length; index++) {
  const item = files[index];
  const stat = fs.lstatSync(path.join(dir, item));
  if (stat.isDirectory() === true && !item.startsWith('.') && !item.startsWith('_')) {
    res.push(path.join(dir, item));
  }
}
fork icon0
star icon0
watch icon1

+ 6 other calls in file

21
22
23
24
25
26
27
28
29
30
31
32


  return result;
}


function resolveSymbolicLink(filePath) {
  const lstat = fs.lstatSync(filePath);
  const resolvedPath = lstat.isSymbolicLink()
    ? path.resolve(path.dirname(filePath), fs.readlinkSync(filePath))
    : false;

fork icon0
star icon0
watch icon0

12
13
14
15
16
17
18
19
20
21
22
23
describe("resolve-symlink", () => {
  if (process.platform !== "win32") {
    it("returns false when filePath is not a symlink", () => {
      const filePath = path.resolve("./not/a/symlink");


      fs.lstatSync.mockReturnValueOnce({
        isSymbolicLink: () => false,
      });


      expect(resolveSymlink(filePath)).toBe(false);
fork icon0
star icon0
watch icon0

+ 11 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)