Table of Contents
Directory operation
Read directory
Home Web Front-end JS Tutorial How to implement fs file system directory operations and file information operations in node.js?

How to implement fs file system directory operations and file information operations in node.js?

Jun 05, 2018 am 09:21 AM
javascript node.js system

This article gives you a detailed analysis of the fs file system directory operation and file information operation methods in node.js, as well as a detailed code explanation. Readers in need can refer to it.

Directory operation

  • If the directory exists, the creation fails

  • Synchronously create the directory fs.mkdirSync(path, [ mode])

const fs = require('fs');
let mkdir = './mkdir';
fs.mkdir(mkdir, (err) => {
  if (err) {
    console.log(`mkdir ${mkdir} file failed~`);
  } else {
    console.log(`mkdir ${mkdir} file success~`);
  }
});
Copy after login

Read directory

  • If there are subdirectories or subfiles in the directory being read, the subdirectories or subdirectories will be The file name of the sub-file is used as the array element of files

  • Read the directory synchronously fs.readdirSync()

const fs = require('fs');
let mkdir = './mkdir';
fs.mkdir(mkdir, (err) => {
  if (err) {
    console.log(`mkdir ${mkdir} file failed~`);
    return false;
  }
  console.log(`mkdir ${mkdir} file success~`);
  let fileName = ['ONE', 'TWO', 'THREE'];
  fileName.forEach((elem) => {
    fs.mkdir(`${mkdir}/${elem}`, (err) => {
      if (err) {
        console.log(`${mkdir}/${elem} failed~`);
        return false;
      }
    });
    fs.readdir(mkdir, (err, files) => {
      if (err) {
        console.log(`readdir ${mkdir} file failed~`);
        return false;
      }
      console.log(`readdir ${mkdir} file success~`);
      console.log(`${files}`);
    });
  });
});
Copy after login

View and modify File or directory information

  • #In the fs module, you can use the stat method or lstat method to view a file or directory. The only difference is that when viewing information about symbolic link files, you must use the lstat method.

  • fs.stat(path, callback(err, stats))

  • ##fs.lstat(path, callback(err, stats))

View file information


Synchronization method to view file information fs.statSync(path);

const fs = require('fs');
let mkdir = './mkdir';

fs.stat(mkdir, (err, stats) => {
  if (err) {
    console.log(`fs.stats ${mkdir} file failed~`);
  } else {
    console.log(`fs.stats ${mkdir} file success~`);
    console.log(stats);
  }
});
Copy after login

stats detailed explanation

Stats {
 dev: 2050,文件或目录所在的设备ID,仅在UNIX有效
 mode: 16877,使用数值形式代表的文件或目录的权限标志
 nlink: 3,文件或目录的硬连接数量
 uid: 0,文件或目录的所有者的用户ID,仅在UNIX有效
 gid: 0,文件或目录的所有者的用户组ID,仅在UNIX有效
 rdev: 0,为字符设备文件或块设备文件所在设备ID,仅在UNIX有效
 blksize: 4096,
 ino: 4197533,文件或目录的索引编号,仅在UNIX有效
 size: 4096,文件尺寸,即文件中的字节数
 blocks: 8,
 atimeMs: 1511846425357.986,
 mtimeMs: 1511846425256.986,
 ctimeMs: 1511846425256.986,
 birthtimeMs: 1511846425256.986,
 atime: 2017-11-28T05:20:25.358Z,文件的访问时间
 mtime: 2017-11-28T05:20:25.257Z,文件的修改时间
 ctime: 2017-11-28T05:20:25.257Z,文件的创建时间
 birthtime: 2017-11-28T05:20:25.257Z 
}
Copy after login

fstat method to query file information

When using the open method or openSync method to open a file and return the file descriptor, you can Use the fstat method in the fs module to query the opened file information

const fs = require('fs');
let mkdir = './mkdir';

fs.open(mkdir, 'r', (err, fd) => {
  if (err) {
    console.log(`open ${mkdir} file failed~`);
    return false;
  }
  fs.fstat(fd, (err, stats) => {
    if (err) {
      console.log(`fstat ${mkdir} file failed~`);
      return false;
    }
    console.log(JSON.stringify(stats));
  })
})
Copy after login

fs.fstat

{
  "dev": 1041887651,
  "mode": 16822,
  "nlink": 1,
  "uid": 0,
  "gid": 0,
  "rdev": 0,
  "ino": 4222124650663107,
  "size": 0,
  "atimeMs": 1519394418412.3062,
  "mtimeMs": 1519394418412.3062,
  "ctimeMs": 1519394418412.3062,
  "birthtimeMs": 1519394418402.2554,
  "atime": "2018-02-23T14:00:18.412Z",
  "mtime": "2018-02-23T14:00:18.412Z",
  "ctime": "2018-02-23T14:00:18.412Z",
  "birthtime": "2018-02-23T14:00:18.402Z"
}
Copy after login

Check whether the file or directory exists


The parameter is a boolean type value

const fs = require('fs');
let mkdir = './mkdir';
fs.exists(mkdir, (exits) => {
  if (exits) {
    console.log(`${exits}, ${mkdir} file exists`);
  } else {
    console.log(`${exits}, ${mkdir} file not exists`)
  }
});
Copy after login

Modify the file access time and modification time

  • fs.utimes(path, atime, mtime, callback(err))

  • Synchronously modify the file access time and modification time fs.utimesSync(path, atime, mtime)

  • // 修改文件访问时间及修改时间都为当前时间
    const fs = require('fs');
    let mkdir = './mkdir';
    fs.utimes(mkdir, new Date(), new Date(), (err) => {
      if (err) {
        console.log(`fs.utimes ${mkdir} file failed~`);
      } else {
        console.log(`fs.utimes ${mkdir} file success~`);
      }
    })
    Copy after login

Modify the permissions of a file or directory

  • Synchronically modify the permissions of a file or directory fs.chmodSync(path, mode);

  • fs.chmod(path, mode, callback(err))

  • mode represents the size of permissions

  • fs The permissions before the .chmod method is triggered are drwxr-xr-x.

  • The permissions after the fs.chmod method is triggered are drw-------.

  • const fs = require('fs');
    let mkdir = './mkdir';
    fs.chmod(mkdirOne, '0600', (err) => {
      if (err) {
        console.log(`fs.chmod ${mkdir} file failed`);
        return false;
      }
      console.log(`fs.chmod ${mkdir} file success~`);
    });
    Copy after login
After using the open method or openSync method to open the file and return the file descriptor, you can use the fchmod method in the fs module to modify the read and write permissions of the file

const fs = require('fs');
let mkdir = './mkdir';
fs.open(mkdir, 'r', (err, fd) => {
  if (err) {
    console.log(`open file ${mkdir} failed~`);
    return false;
  }
  fs.fchmod(fd, '0600', (err) => {
    if (err) {
      console.log(`fs.fchmod ${mkdir} file failed~`);
      return false;
    }
    console.log(`fs.fchmod ${mkdir} file success~`);
  })
});
Copy after login
The above is what I compiled for everyone Yes, I hope it will be helpful to everyone in the future.

Related articles:

How to create an instruction to upload photos in AngularJS (detailed tutorial)

How to do it in javaScript Dynamically adding instances of Li elements

How to modify the default style in elementui?

The above is the detailed content of How to implement fs file system directory operations and file information operations in node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CUDA's universal matrix multiplication: from entry to proficiency! CUDA's universal matrix multiplication: from entry to proficiency! Mar 25, 2024 pm 12:30 PM

General Matrix Multiplication (GEMM) is a vital part of many applications and algorithms, and is also one of the important indicators for evaluating computer hardware performance. In-depth research and optimization of the implementation of GEMM can help us better understand high-performance computing and the relationship between software and hardware systems. In computer science, effective optimization of GEMM can increase computing speed and save resources, which is crucial to improving the overall performance of a computer system. An in-depth understanding of the working principle and optimization method of GEMM will help us better utilize the potential of modern computing hardware and provide more efficient solutions for various complex computing tasks. By optimizing the performance of GEMM

Huawei's Qiankun ADS3.0 intelligent driving system will be launched in August and will be launched on Xiangjie S9 for the first time Huawei's Qiankun ADS3.0 intelligent driving system will be launched in August and will be launched on Xiangjie S9 for the first time Jul 30, 2024 pm 02:17 PM

On July 29, at the roll-off ceremony of AITO Wenjie's 400,000th new car, Yu Chengdong, Huawei's Managing Director, Chairman of Terminal BG, and Chairman of Smart Car Solutions BU, attended and delivered a speech and announced that Wenjie series models will be launched this year In August, Huawei Qiankun ADS 3.0 version was launched, and it is planned to successively push upgrades from August to September. The Xiangjie S9, which will be released on August 6, will debut Huawei’s ADS3.0 intelligent driving system. With the assistance of lidar, Huawei Qiankun ADS3.0 version will greatly improve its intelligent driving capabilities, have end-to-end integrated capabilities, and adopt a new end-to-end architecture of GOD (general obstacle identification)/PDP (predictive decision-making and control) , providing the NCA function of smart driving from parking space to parking space, and upgrading CAS3.0

Which version of Apple 16 system is the best? Which version of Apple 16 system is the best? Mar 08, 2024 pm 05:16 PM

The best version of the Apple 16 system is iOS16.1.4. The best version of the iOS16 system may vary from person to person. The additions and improvements in daily use experience have also been praised by many users. Which version of the Apple 16 system is the best? Answer: iOS16.1.4 The best version of the iOS 16 system may vary from person to person. According to public information, iOS16, launched in 2022, is considered a very stable and performant version, and users are quite satisfied with its overall experience. In addition, the addition of new features and improvements in daily use experience in iOS16 have also been well received by many users. Especially in terms of updated battery life, signal performance and heating control, user feedback has been relatively positive. However, considering iPhone14

Always new! Huawei Mate60 series upgrades to HarmonyOS 4.2: AI cloud enhancement, Xiaoyi Dialect is so easy to use Always new! Huawei Mate60 series upgrades to HarmonyOS 4.2: AI cloud enhancement, Xiaoyi Dialect is so easy to use Jun 02, 2024 pm 02:58 PM

On April 11, Huawei officially announced the HarmonyOS 4.2 100-machine upgrade plan for the first time. This time, more than 180 devices will participate in the upgrade, covering mobile phones, tablets, watches, headphones, smart screens and other devices. In the past month, with the steady progress of the HarmonyOS4.2 100-machine upgrade plan, many popular models including Huawei Pocket2, Huawei MateX5 series, nova12 series, Huawei Pura series, etc. have also started to upgrade and adapt, which means that there will be More Huawei model users can enjoy the common and often new experience brought by HarmonyOS. Judging from user feedback, the experience of Huawei Mate60 series models has improved in all aspects after upgrading HarmonyOS4.2. Especially Huawei M

What are the computer operating systems? What are the computer operating systems? Jan 12, 2024 pm 03:12 PM

A computer operating system is a system used to manage computer hardware and software programs. It is also an operating system program developed based on all software systems. Different operating systems have different users. So what are the computer systems? Below, the editor will share with you what computer operating systems are. The so-called operating system is to manage computer hardware and software programs. All software is developed based on operating system programs. In fact, there are many types of operating systems, including those for industrial use, commercial use, and personal use, covering a wide range of applications. Below, the editor will explain to you what computer operating systems are. What computer operating systems are Windows systems? The Windows system is an operating system developed by Microsoft Corporation of the United States. than the most

Detailed explanation of how to modify system date in Oracle database Detailed explanation of how to modify system date in Oracle database Mar 09, 2024 am 10:21 AM

Detailed explanation of the method of modifying the system date in the Oracle database. In the Oracle database, the method of modifying the system date mainly involves modifying the NLS_DATE_FORMAT parameter and using the SYSDATE function. This article will introduce these two methods and their specific code examples in detail to help readers better understand and master the operation of modifying the system date in the Oracle database. 1. Modify NLS_DATE_FORMAT parameter method NLS_DATE_FORMAT is Oracle data

Differences and similarities of cmd commands in Linux and Windows systems Differences and similarities of cmd commands in Linux and Windows systems Mar 15, 2024 am 08:12 AM

Linux and Windows are two common operating systems, representing the open source Linux system and the commercial Windows system respectively. In both operating systems, there is a command line interface for users to interact with the operating system. In Linux systems, users use the Shell command line, while in Windows systems, users use the cmd command line. The Shell command line in Linux system is a very powerful tool that can complete almost all system management tasks.

Where is the system font storage path? Where is the system font storage path? Feb 19, 2024 pm 09:11 PM

In which folder are the system fonts located? In modern computer systems, fonts play a vital role, affecting our reading experience and the beauty of text expression. For some users who are keen on personalization and customization, it is particularly important to understand the storage location of system fonts. So, in which folder are system fonts stored? This article will reveal them one by one for everyone. In the Windows operating system, system fonts are stored in a folder called "Fonts". This folder is located in the Win C drive by default.

See all articles