Home > Web Front-end > JS Tutorial > body text

How to operate fs files in node.js

小云云
Release: 2018-02-26 09:26:19
Original
1418 people have browsed it

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

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

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);
  }
});
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 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"
}
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 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
  • 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~`);
});
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 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~`);
  })
});
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!