search

Home  >  Q&A  >  body text

node.js - 一个fs.statSync的问题

"use strict";
var fs = require('fs');
var colors = require('colors/safe');
fs.readdir(process.cwd(), function (err, files) {
    files.forEach(function (item, index, array) {
        fs.statSync(item, function (err, stat) {
            if (stat.isDirectory()) {
                console.log(colors.blue(item + '/'));
            }
            else if (stat.isFile()) {
                console.log(colors.green(item));
            }
        });
    });
});

这个程序本来是想打印出当前目录下的文件的,但是如果我把fs.stat换成fs.statSync后,就无法输出了,这是为啥呢? node的版本是v0.12.7

迷茫迷茫2777 days ago547

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 12:00:13

    Because statSync is a synchronization method, the result is obtained directly, that is, stat = fs.statSync(item) and then judge stat.isDirectory()

    reply
    0
  • 阿神

    阿神2017-04-17 12:00:13

    Let’s take a look at the many methods provided by the File System module of nodejs. These methods can be roughly divided into two categories: one is asynchronous + callback; the other is synchronous. Among them, stat belongs to the former, and statSync belongs to the latter. Let’s take a look at the difference:

    1.异步版:fs.stat(path,callback):
        path是一个表示路径的字符串,callback接收两个参数(err,stats),其中stats就是fs.stats的一个实例;
      
    2.同步版:fs.statSync(path)
       只接收一个path变量,fs.statSync(path)其实是一个fs.stats的一个实例;
    
    3.再来看fs.stats有以下方法:
        stats.isFile()
        stats.isDirectory()
        stats.isBlockDevice()
        stats.isCharacterDevice()
        stats.isSymbolicLink() (only valid with fs.lstat())
        stats.isFIFO()
        stats.isSocket()
    

    After reading this, you will understand.

    reply
    0
  • Cancelreply