search
HomeWeb Front-endJS TutorialHow to operate fs files in node.js

How to operate fs files in node.js

Feb 26, 2018 am 09:26 AM
javascriptnode.jsmethod

This article mainly 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. Hope it helps everyone.

Directory operation

  • If the directory exists, the creation fails

  • Create the directory synchronously 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~`);
  }
});

Read directory

  • If there is a directory in the read directory For subdirectories or subfiles, the file name of the subdirectory or subfile will be used as the array element of files

  • Synchronously read the directory 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}`);
    });
  });
});

View and modify file or directory information

  • In the fs module, you can use the stat method or The lstat method views 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);
  }
});

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 
}

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));
  })
})

fs.fstat result

{
  "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"
}

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`)
  }
});

Modify 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~`);
  }
})


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
  • The permissions before the fs.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~`);
});

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 reading and writing of the file Permissions

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~`);
  })
});

Related recommendations:

How to solve the asynchronous reading and writing of synchronization results in the fs module in node.js

Detailed explanation of the example of reading and writing files based on the fs core module based on node.js

Introduction to the fs file system example in nodeJS

The above is the detailed content of How to operate fs files in node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft