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
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
- 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
- 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!

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

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.

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

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.

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 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.

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

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
A free and powerful IDE editor launched by Microsoft
