Introduction to the

Nodejs uses asynchronous IO to improve server processing efficiency. One very important aspect of IO is file IO. Today we’ll cover file systems and IO operations in NodeJS in more detail.

File system module in NodeJS

Nodejs has a very important module called FS. This module provides a number of very useful functions to access and interact with file systems.

For a quick look, FS provides the following file manipulation methods:

  • Fs.access (): checks whether the file exists and whether Node.js has permission to access it.
  • Fs.appendfile (): Appends data to a file. If the file does not exist, the file is created.
  • Fs.chmod (): Changes the permissions of a file (specified by the filename passed in). Related methods: fs.lchmod(), fs.fchmod().
  • Fs.chown (): Changes the owner and group of the file (specified by the filename passed in). Related methods: fs.fchown(), fs.lchown().
  • Fs.close (): Closes the file descriptor.
  • Fs.copyfile (): copies a file.
  • Fs.createreadstream (): Creates a readable file stream.
  • Fs.createwritestream (): Creates a writable file stream.
  • Fs.link (): creates a hard link to the file.
  • Fs.mkdir (): Creates a folder.
  • Fs.mkdtemp (): Creates a temporary directory.
  • Fs.open (): Sets the file mode.
  • Fs.readdir (): reads the contents of a directory.
  • Fs.readfile (): reads the contents of a file. Related methods: fs.read().
  • Fs.readlink (): Reads the value of a symbolic link.
  • Fs.realpath (): Puts relative file path Pointers (.,..) Resolves to the full path.
  • Fs.rename (): renames a file or folder.
  • Fs.rmdir (): Deletes a folder.
  • Fs.stat (): Returns the status of the file (specified by the filename passed in). Related methods: fs.fstat(), fs.lstat().
  • Fs.symlink (): creates a symbolic link for a file.
  • Fs.truncate (): truncates the file identified by the passed file name to the specified length. Related methods: fs.ftruncate().
  • Fs.unlink (): deletes a file or symbolic link.
  • Fs.unwatchfile (): Stops monitoring changes on files.
  • Fs.utimes (): Changes the timestamp of the file (specified by the filename passed in). Related methods: fs.futimes().
  • Fs.watchfile (): Starts monitoring changes on files. Related methods: fs.watch()
  • Fs.writefile (): writes data to a file. Related method: fs.write().

Note that the methods provided by FS are asynchronous, and by asynchronous I mean they provide callback functions that trigger processing logic asynchronously.

Let’s take a simple example of reading a file:

const fs = require('fs')

fs.readFile('/tmp/flydean.txt'.'utf8' , (err, data) = > {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})
Copy the code

In the above example, we read a flydean.txt file from the/TMP file. The abnormal and normal data are processed respectively in callback function.

Fs provides synchronous method calls as well as asynchronous methods, which are followed by Sync:

const fs = require('fs')

try {
  const data = fs.readFileSync('/tmp/flydean.txt'.'utf8')
  console.log(data)
} catch (err) {
  console.error(err)
}
Copy the code

Let’s see what happens when we rewrite the above method to the synchronous method.

The difference is that the synchronous method blocks until the file has been read.

Promise version of FS

There’s no reason for asynchronous operations to be less Promsie, because fs is all asynchronous, and if you don’t want to use FS via callback, FS also provides a Promise version.

Again with the readfile example, let’s see what happens if we use promises:

const fs = require('fs/promises');

(async function(path) {
  try {
    await fs.readFile(path, 'utf8');console.log('Reading the file succeeded${path}`);
  } catch (error) {
    console.error('Error:', error.message);
  }
})('/tmp/flydean.txt');
Copy the code

The PROMISE version of FS is under FS/Promises. In the example above we use async and await to write asynchronous programs synchronously. It is very convenient.

File descriptor

The file descriptor is the value returned in NodeJS when we use the fs.open method.

We can use this file descriptor to further interact with files.

const fs = require('fs')

fs.open('/tmp/flydean.txt'.'r'.(err, fd) = > {
  Fd is the file descriptor.
})
Copy the code

The second argument to the open method above means that the file is opened read-only.

Let’s take a look at common file system flags:

  • ‘r’: opens the file for reading. If the file does not exist, an exception occurs.

  • ‘r+’: opens the file for reading and writing. If the file does not exist, an exception occurs.

  • ‘w’: opens the file for writing. Create a file if it doesn’t exist, and truncate it if it does.

  • ‘W +’: opens the file for reading and writing. Create a file if it doesn’t exist, and truncate it if it does.

  • ‘A ‘: Opens the file for append. If the file does not exist, it is created.

  • ‘A +’: opens the file for reading and append. If the file does not exist, it is created.

Of course, the above example can also be overwritten with openSync:

const fs = require('fs')

try {
  const fd = fs.openSync('/tmp/flydean.txt'.'r')}catch (err) {
  console.error(err)
}
Copy the code

Fs. stat Indicates the file status

Nodejs provides a fs.Stats class that describes the status of a file.

Stats provides some very useful methods to determine the state of a file:

Stats.isdirectory (), stats.isfile (), stats.issocket (), stats.issymbolicLink (), stats.ctime, etc.

Stats also provides some options for file timing:

  • Atime “Access Time” – Time when file data was last accessed.
  • Mtime “Modification Time” – Time when file data was modified last time.
  • Ctime “Change time” – The time when the file state was last changed (index node data was modified).
  • Birthtime Create Time – Specifies the time when a file is created.

Let’s see how to get fs.stat:

const fs = require('fs')
fs.stat('/tmp/flydean.txt'.(err, stats) = > {
  if (err) {
    console.error(err)
    return
  }

  stats.isFile() //true
  stats.isDirectory() //false
  stats.isSymbolicLink() //false
  stats.size // File size
})
Copy the code

Stats will be passed as a callback argument to fs.stat. With fs.stats, we do another set of operations.

Fs file read and write

We have introduced how to use fs to read files. Now we will introduce how to use FS to write files.

const fs = require('fs')

const content = 'www.flydean.com'

fs.writeFile('/tmp/flydean.txt', content, err= > {
  if (err) {
    console.error(err)
    return
  }
  // The file was successfully written.
})
Copy the code

Callback (); callback ();

const fs = require('fs')

const content = 'www.flydean.com'

try {
  const data = fs.writeFileSync('/tmp/flydean.txt', content)
  // The file was successfully written.
} catch (err) {
  console.error(err)
}
Copy the code

WriteFile also supports an additional options parameter. In the options parameter, we can specify the flag bits that the file is written to, such as r+, W +, A, A +, and so on.

fs.writeFile('/tmp/flydean.txt', content, { flag: 'a+' }, err= > {})
Copy the code

Of course, in addition to using a+ to represent append to the end of the file, FS also provides a appendFile method to output to the end of the file:

const fs = require('fs')

const content = 'www.flydean.com'

fs.appendFile('/tmp/flydean.txt', content, err= > {
  if (err) {
    console.error(err)
    return
  }
  // File append succeeded.
})
Copy the code

Fs folder operations

Where there are files, there are folders. Fs provides a series of folder operations, such as:

Mkdir, readdir, rename rmdir operations.

Readdir is relatively responsible, for example:

const fs = require('fs')
const folderPath = '/tmp'

fs.readdir(folderPath, function(err,files){
    if(err){
        console.log(err);
    }
    files.map(file= > console.log(file));
})

fs.readdirSync(folderPath).map(fileName= > {
    console.log(fileName);
})
Copy the code

In the above example, we used readdir and readdirSync respectively to read files in a directory.

You can see the difference.

The path operation

Finally, we’ll look at a path operation specifically related to file that provides utilities for handling file and directory paths.

Path stands for path. We use path in the following way:

const path = require('path')
Copy the code

Why do WE need path? We know that there are about two styles of operating systems in the world, Windows and POSIX.

Paths are expressed differently in the two operating systems. So, we need a generic path module to resolve this difference for us.

We can see this difference in an example:

On Windows:

path.basename('C:\\temp\\myfile.html');
// Return: 'myfile.html'
Copy the code

On the POSIX:

path.basename('C:\\temp\\myfile.html');
// Return: 'C:\ temp\ myfile.html'
Copy the code

Let’s first look at the path.basename method, which returns the last part of the path.

In the example above, we pass a Windows-style path to Windows, so it will parse normally and get normal results.

In a POSIX environment, we pass a Windows-style path that doesn’t parse properly and returns the entire result.

Path also has a number of useful methods, such as:

const notes = '/tmp/notes.txt'

path.dirname(notes) // /tmp
path.basename(notes) // notes.txt
path.extname(notes) // .txt

path.join('/'.'tmp'.'notes.txt') //'/tmp/notes.txt'

path.resolve('notes.txt') //'/Users/flydean/notes.txt' parses from the current directory to get the absolute path of the relative path

path.normalize('/tmp/flydean.. //test.txt') /// TMP /test.txt Attempts to calculate the actual path
Copy the code

Author: Flydean program stuff

Link to this article: www.flydean.com/nodejs-file…

Source: Flydean’s blog

Welcome to pay attention to my public number: “procedures those things” the most popular interpretation, the most profound dry goods, the most concise tutorial, many you do not know the small skills you find!