Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Which module of nodejs can manipulate files?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "which module of nodejs can operate files". In daily operation, I believe that many people have doubts about which module of nodejs can operate files. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "which module of nodejs can operate files". Next, please follow the editor to study!

The File system module of nodejs can manipulate files. Fs (File system) module is a functional module provided by nodejs to access the local file system. Fs module can be used to create files and directories, write, delete and other operations.

The operating environment of this tutorial: windows7 system, nodejs 12.19.0, Dell G3 computer.

1. Brief introduction of fs module. Basic concept

Fs (file system) module is a functional module provided by nodejs to access the local file system, which makes JavaScript running in the nodejs environment have the ability to read and write local files directly.

Fs module is one of the core modules of nodejs. As long as nodejs is installed, it can be used directly and does not need to be installed separately. Introducing the fs module is very simple:

Let fs = require ('fs')

Then you can call the relevant interface of the fs module to read and write the file system directly.

The fs module mainly provides the following interface classes:

Fs.Dir, catalog class. Can be understood as a folder.

Fs.Dirent, catalog item class. Obtained from the return value of the Dir class, it represents a subitem under that directory, which may be a file or subdirectory.

Fs.FSWatcher, the file listener class, can create a listener for a file that triggers a callback when the file changes.

Fs.StatWatcher, the return value type after calling the fs.watchFile () method, is mainly used to help control the event loop.

Fs.ReadStream, read stream. This class is required when streaming files.

Fs.Stats, file meta-information class. Through this class, you can get file-related information (such as file type, file size, file descriptor, and so on).

Fs.WriteStream, write stream. Need to be used when streaming data.

In addition to the above classes, the fs module also provides a number of instance methods that can be called directly through fs, such as the method reafFile for reading files:

Let fs = require ('fs'); fs.readFile ('. / README.md', function (err, data) = {if (err) throw err;. / / process data})

This function reads the file asynchronously, taking the possible thrown exception as the first parameter of the callback function (designed to "force" or "remind" the developer to handle possible exceptions). The real document data is used as the second parameter.

Almost all of the default read and write functions in the fs module are asynchronous, but it also provides synchronous versions of these functions, usually followed by Sync. For example, the above code can also be rewritten in readFileSync:

Let fs = require ('fs'); try {let data = fs.readFileSync ('. / README.md', 'utf8');} catch (e = {console.error (e);})

In most cases, nodejs recommends using an asynchronous version of the read-write function to improve system performance. If you want to use a synchronous version of the function, you should use try catch to catch exceptions as much as possible to prevent the main thread from crashing due to read and write failures.

two。 File path

Since it is a file system module, it is necessary to find the file you need to operate according to the file path. The path types supported by the fs module fall into three categories: string, Buffer, and URL objects.

(1)。 String

String classes are the most commonly used path types, including absolute and relative paths. The absolute path refers to the path relative to the root of the file system, while the relative path is relative to the current working directory (that is, the directory where the node command was run, which can be obtained through process.cwd ()).

There are some differences between windows and other operating systems when using absolute paths. Because in most other operating systems, the drive has a unique root directory; on windows, there are multiple separate drives (such as C disk, D disk, etc.). From the point of view of writing, the absolute path usually starts with /, indicating the root directory of the drive:

Fs.readFile ('/ README.md', (err, data) = > {...})

On the windows, it starts with the drive:

Fs.readFile (err, data) = > {...})

We know that windows generally uses a backslash\ as the path delimiter. However, it is compatible in nodejs and can be correctly identified using slashes or backslashes, so the following is also correct:

Fs.readFile ('d:\\ nodejs\ README.md', (err, data) = > {...})

It should be noted that when you use fs.readdir ('user') to read the C disk directory, you are actually reading the user root directory c:\\ user\ root. You must add a double slash or a double backslash before you can read the real c disk root directory: fs.readdir ('cJR _ user _ xxx').

The relative path is relative to the current working directory, usually starting with.. / (fallback to the parent directory),. / (current directory), or a directory entry under the current path. Such as:

/ / README.md file fs.readFileSync ('.. / README.md') in the directory above the current directory; / / README.mdfs.readFileSync ('. / nodejs/README.md') in the nodejs folder under the current directory; fs.readFileSync ('nodejs/README.md')

The beginning of. / indicates the current directory and can be omitted directly.

(2)。 Buffer

There is little difference between Buffer type paths and strings, except that some operating systems treat file paths as binary byte sequences, so it is usually necessary to convert string paths to binary byte sequences in the way of Buffer.from ('README.md'). Since this type of operating system is rarely used, it will not be described in detail here.

(3)。 URL

URL (uniform resource locator) is a general resource location scheme, which regards any resources (including local files) as network resources, and then locates them in a unified way.

The fs module only supports URL objects that use the file protocol, which is prefixed with file:/// and the path format is as follows:

/ / under windows, locate a file on a host. / / it is generally used to read and write the shared folder fs.readFileSync (new URL ('file:/// hostname / README.md')) in the local area network; / / locate the local resource fs.readFileSync (new URL (' file:///c:/README.md'));)

The above two writing methods are aimed at the windows platform, the first is mainly used for reading shared files in the local area network, and the second is used for reading and writing local files.

For other platforms, the format of url is as follows:

Fs.readFileSync (new URL ('file:///nodejs/README.md'));)

It will be converted to the absolute path: / nodejs/README.md. Paths of type URL do not support relative paths.

2. Common classes of fs module

In view of the large number of interfaces of the fs module, we will not discuss them one by one here. If you are interested, please refer to the nodejs Chinese Network-fs module. This article mainly introduces some api commonly used in the following API classes, which can basically meet the needs of most file system operations:

Fs.Dir

Fs.Dirent

Fs.ReadStream

Fs.Stats

Fs.WriteStream

1. Fs.Dir (v12.12)

This is an abstract class for directories, or folders, by the fs module. Calling the fs.opendir (), fs.opendirSync (), or fsPromises.opendir () methods returns an object of type Dir to manipulate the opened directory.

For example, if we want to traverse all the subdirectories and files under the current folder, we can use the following code (v12.12 or above is available):

Async function getChild (path) {/ / reads the directory subkey and returns a promise let dir = await fs.promises.opendir (path); for await (let dirent of dir) {console.log (dirent.name);}}

There are three ways to close a directory: dir.close (), dir.close (callback), and dir.closeSync ().

Dir.close () returns a promise, and registering the then method with it can execute a callback function after the directory is closed, such as dir.close (). Then ((e) = > {...}); dir.close (callback) is an asynchronous method to close the directory, passing in the callback function directly, which is called after the file is closed; dir.closeSync () is a synchronous method to close the directory, and subsequent code is executed only after the directory is closed successfully.

The value of dir.path is the path of the current directory, that is, the path passed in when the opendir method is called.

There are three ways to read the directory entries of this directory: dir.read (), dir.read (callback), and dir.readSync ().

Dir.read () returns an promise array or null, which is responsible for reading each directory entry, which is mainly used for traversing the async function:

Async function read (path) {let dir = await fs.promises.opendir (path); for await (let dirent of dir.read ()) {...}}

Dir.read (callback) is an asynchronous version of a read catalog entry. Each time a subitem is read, callback;dir.readSync () is called to read the synchronous version of the catalog entry, returning an array or null of type Dirent.

2. Fs.Dirent (v10.10)

Catalog item class. When you read a directory through the fs.opendir () method, each of its children is a Dirent class object, and each Dirent object may be a subdirectory or a file. Each Dirent object consists of a file name and a file type.

The method provided by fs.Dirent is mainly used to determine the type of directory item:

Dirent.isBlockDevice (), whether it is a block device.

Dirent.isCharacterDevice (), whether it is a character device.

Dirent.isDirectory (), whether it is a system directory.

Dirent.isFIFO (), whether it is a first-in first-out channel.

Dirent.isFile (), whether it is a normal file.

Dirent.isSocket (), whether it is a socket.

Dirent.isSymbolicLink (), whether it is a symbolic link, namely a shortcut.

In addition, the value of dirent.name is the name of the directory entry.

3. Fs.ReadStream

Read stream class, which is used to stream read files. This class is created and returned by fs.createReadStream ().

Fs.ReadStream supports three events:

Close, read stream close event.

Open, read stream open event.

Ready, the read stream ready event, is triggered immediately after the open event occurs.

The callback function takes the file descriptor FD as an argument for subsequent operations on the file.

A fs.ReadStream instance has three instance properties:

ReadStream.bytesRead, the number of bytes read.

ReadStream.path, file path.

ReadStream.pending, whether the file is ready (the value is true before the ready event occurs and becomes false after the file event occurs).

4. Fs.Stats

Provides a description of the file information. Calling fs.stat (), fs.lstat (), and fs.fstat () returns an object of that type.

An instance of fs.Stats contains the following properties:

Stats {dev: 2114, / / numeric identifier of the device ino: 48064969, / / index number of the device mode: 33188, / / file type and mode nlink: 1, / / number of hard links to the file uid: 85, / / identifier of the file owner gid: 100, / / identifier of the group that owns the file rdev: 0, / / numeric device table identifier size: 527 / / File size In bytes blksize: 4096, / / size of file system block blocks: 8, / number of blocks allocated by the file system to the current file atimeMs: 1318289051000.1, / / time last accessed mtimeMs: 1318289051000.1, / / time last modified ctimeMs: 1318289051000.1, / / time when the file status was last changed birthtimeMs: 1318289051000.1, / / creation time of the file atime: 10 Oct 2011 23:24:11 GMT, / / another format of the above four times mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT}

Each Stats object can also return a result of type bigint, each of which is of type bigint rather than the number type above, which is not detailed here.

At the same time, it also has the same seven instance methods as Dirent to determine the current device type, please refer to the above Dirent.

5. Fs.WriteStream

Write stream class for streaming data writing. It is created and returned by fs.createWriteStream ().

Similar to fs.ReadStream, it also has three events: close, open, and ready, both of which are used in the same way.

Each WriteStream instance also has three instance properties: writeStream.bytesWritten, writeStream.path, and writeStream.pending, which represent the number of bytes currently written, the path to write to the stream file, and whether they are ready, similar to ReadStream.

Third, the common methods of fs module

The fs module provides many functions for reading and writing file system resources, and the classes introduced in the previous section mainly encapsulate the results of the operations of these functions. Here are some common methods:

1. Fs.access (path [, mode], callback)

Check the availability of files.

The first parameter, path, is the file path and can be of type string, Buffer, or URL

The second parameter is the type to check, and possible values include fs.constants.F_OK (present, default), fs.constants.R_OK (readable), and fs.constants.W_OK (writable).

The third parameter is the callback function. If the check fails, an Error object will be passed, otherwise undefined will be passed.

For example, if we need to check whether package.json exists in the current folder, we can write:

Fs.access ('package.json', fs.constants.F_OK, (err) = > {if (err) {. / / File exists} else {. / / File does not exist}})

In general, you should not read or write to a file immediately after checking the availability of the file, because the state of the file may change between checking the availability of the file and actually reading and writing the file (for example, other processes manipulate the file). This can invalidate the file availability check. Therefore, the fs.access method is usually only used to check the availability of the file, and if you want to read and write the file, you can directly call the method of reading and writing the file, and then judge whether the file is available according to the possible exceptions received by the callback function.

There is also a synchronous version of the method: fs.accessSync (path [, mode]), and the first two parameters are the same as the asynchronous version. This method returns undefined when the file check is successful, otherwise an exception will be thrown. The usage is as follows:

Try {fs.accessSync ('package.json', fs.constants.R_OK | fs.constants.W_OK); console.log (' can read and write');} catch (err) {console.error ('no access');} 2. Fs.appendFile (path, data [, options], callback)

Append data to the file.

Path supports string, Buffer, and URL types

Data is the data to be appended, which can be a string or a Buffer instance

Options is the configuration object and contains three parameters:

Encoding, encoding method. Default is utf8.

Mode, mode, default is 0o666. This parameter is the permission description of the file, and 0o666 indicates that each user has read and write permissions.

Flag, file operation mode. Default is a, that is, append.

Callback is the callback function after the function has been executed. If the append fails, the first parameter is the error object, otherwise it is undefined. Examples are as follows:

Fs.appendFile ('README.md',' this is the data to be added, (err) = > {if (err) {console.log ('data append failed');} else {console.log ('data append successful');}})

The synchronous version of this method is fs.appendFileSync (path, data [, options]). Like accessSync, it only removes the last parameter, callback, and determines the result of the operation by returning a value. I will not repeat the example here.

3. Fs.chmod (path, mode, callback)

Modify the permissions of the file.

Each file in the file system has read, write, and execute permissions, represented by r, w, and x. The weight of r is 4, the weight of w is 2, and the weight of x is 1, that is, when the user has read permission, the permission value adds 4, when the user has write permission, the permission value adds 2, and when he has execution permission, the permission value adds 1.

Permission type weight read permission 4 write permission 2 execute permission 1

This weight assignment makes the permission values of any kind of permission different, so only an octal number is needed to indicate which permissions a user has on a file.

For example, if a user has read and write permission to a file but does not have the right to execute, his limit value is 4 + 2 + 0 = 6. If you have all three permissions at the same time, the limit value is 4 + 2 + 1 = 7.

For a file, there are three types of users in the system: the owner of the file, the user group that owns the file, and other users. The file system uses three octal numbers to represent the permissions of these three types of users on a file. For example, when the weight value of a file is 0o761, it means:

The owner of the file has read, write and execute permissions: 7 = 4 + 2 + 1

Members of the user group to which the file belongs have read and write permissions: 6 = 4 + 2 + 0

Other members only have executive permission: 1 = 0 + 0 + 1

The fs.chmod method is used to modify the permissions of a file. It can pass in three parameters, namely, the file path, the weight limit, and the callback function. The permission value is the three octal numbers mentioned above, such as 0o761; if the modification fails, the callback function receives the exception object, otherwise there are no parameters.

The synchronous version of this method is fs.chmodeSync (path, mode), and its usage is the same as that of other synchronization methods.

4. Fs.chown (path, uid, gid, callback)

Modify the owner of the file.

The first parameter is the file path; the second parameter is the user identifier of the new file owner; the third parameter is the identifier of the user group to which the file belongs, and the last parameter is the callback function after execution.

Both uid and gid are of type number, and the only id,callback assigned by the file system to each user and user group will get an error object if the operation fails.

The synchronous version of this method is fs.chownSync (path, uid, gid), and the method is the same as other synchronization methods.

5. Fs.close (fd, callback)

Close a file asynchronously.

The first parameter, fd, is a file descriptor of a numeric type assigned by the file system when a file is opened by calling fs.open; when the file fails to close, callback gets an exception object. Such as:

Fs.open ('README.md',' asides, (err, fd) = > {... Fs.close (fd, (err) = > {if (err) {} / / shutdown failed});})

The asynchronous version of this method is fs.closeSync (fd).

6. Fs.constants

For constants provided by the fs module, see fs constants.

7. Fs.copyFile (src, dest [, mode], callback)

Copy a file.

The first parameter src is the address of the copy source, and the data type is the same as path.

The second parameter, dest, is the destination address, and the data type is the same as path.

The third optional parameter is the copy parameter, and by default, the target file is created or overwritten (when the file already exists). In addition to this default value, there are three optional values:

"fs.constants.COPYFILE_EXCL? if dest already exists, the copy operation will fail."

Fs.constants.COPYFILE_FICLONE? the copy operation attempts to create a copy-on-write (copy-on-write) link. If the platform does not support copy-on-write, a backup copy mechanism is used.

Fs.constants.COPYFILE_FICLONE_FORCE? the copy operation attempts to create a copy-on-write link. If the platform does not support copy-on-write, the copy operation will fail.

The fourth parameter is a callback function after execution, which, like other asynchronous functions, also receives an exception object on failure.

Its synchronized version is fs.copyFileSync (src, dest [, mode]).

8. Fs.createReadStream (path [, options])

Create a read stream. Common uses are:

Let fs = require ('fs') Let rs = fs.createReadStream ('. / 1.txtread, {highWaterMark:3, / / how many bytes are read in a file at a time. Default is 64 bytes 1024 flags:'r', / / default is'r 'autoClose:true, / / start:0 is automatically turned off after reading, / / the start position of the file is read end:3, / / the stream is a closed interval including both start and end encoding:'utf8' / / default null}) Rs.on ("open", () = > {console.log ("File Open")}); / / automatically triggers the data event until it has been read rs.on ('data', (data) = > {console.log (data);}); 9. Fs.createWriteStream (path [, options])

Create a write stream. Common uses are:

Const fs=require ('fs'); const path=require (' path'); let writeStream=fs.createWriteStream ('. / test/b.js', {encoding:'utf8'}); / / read file error event writeStream.on ('error', (err) = > {console.log (' exception:', err);}); / / opened file event writeStream.on ('open', (fd) = > {console.log (' file opened:', fd)) }); / / file write completion event writeStream.on ('finish', () = > {console.log (' write completed..'); console.log ('read file contents:', fs.readFileSync ('. / test/b.js', 'utf8')); / / print written content console.log (writeStream);}) / / File close event writeStream.on ('close', () = > {console.log (' file closed!') WriteStream.write ('this is what I'm going to do'); writeStream.end (); 10. A set of functions based on file descriptors

For example, fs.fchown (fd, callback), fs.fchmod (fd, callbakc), etc., it replaces the first parameter from path to the corresponding file descriptor. Before using this method, you need to open the file through fs.open` to obtain the file descriptor. I will not elaborate here.

11. Fs.mkdir (path [, options], callback)

Create a directory (that is, folder).

The first parameter, path, is the path of the folder to be created

The second parameter, options, supports two parameters:

Recursive, whether to create a parent directory recursively. Default is false.

Mode, the permission of the created folder. The default is 0o777.

The third parameter is the finished callback function, whose first argument is the possible exception object, and when recursive is true, it also gets a path parameter whose value is the first directory created by the current operation.

When the directory to be created already exists, if recursive is false, an exception will be thrown, otherwise no action will be performed.

The use of creating a directory is as follows:

Fs.mkdir ('nodejs/lib', {recursive: true}, (err, path) = > {...})

The code attempts to create a lib folder within the nodejs folder under the current path, and recursively creates a parent directory. That is, if there is no nodejs folder in the current directory, create it first. After creation, if the nodejs folder is newly created, path is its path; if nodejs already exists, path is the path to the newly created lib folder.

The synchronous version of this method is fs.mkdirSync (path [, options]).

12. Fs.open (path [, flags [, mode]], callback)

Open a file.

The first parameter is the path of the file to be opened

The second parameter is open, such as r (read-only), w (write-only), a (append), etc.

The third parameter is file permissions, which defaults to 0o666 (read and write permissions)

The last parameter is the callback function, which takes two arguments, the first is the exception object that may be thrown, and the second is the file descriptor FD of the numeric type assigned by the file system to the opened file.

Such as:

Fs.open ('README.md',' ritual, (err, fd) = > {... Fs.close (fd, (err) = > {})})

Its synchronized version is fs.openSync (path [, flags [, mode]]).

13. Fs.opendir (path [, options], callback)

Open a directory.

The first parameter is the path to the directory

The second parameter contains two parameters:

Encoding, encoding type, default utf8

BufferSize, the number of directory entries to be buffered when operating the directory. The default is 32. The higher the value, the better the performance, but the greater the memory consumption.

The third argument is callback, which is the callback function after opening the directory. The callback function accepts two values, one is a possible exception object, and the other is an open directory object of type fs.Dir.

Its synchronized version is fs.opendirSync (path [, options]).

14. Fs.readFile (path [, options], callback)

Read file data asynchronously.

By default, this method opens the file with fs.open and automatically closes the file after reading it. Therefore, calling this method does not require manual opening and closing of the file, but if you need to manipulate the file frequently, the method will cause the file to be opened and closed repeatedly, resulting in performance degradation.

Path can be a file descriptor in addition to a file path. If a file descriptor is passed in, the file is not closed by default after the read is complete, and subsequent reads continue backward from the last read location.

Options supports the following two parameters:

Encoding, encoding format. Default is null. 'utf8'' is generally passed in for actual use.

Flag, read mode, default is read-only r

If you only need to specify the encoding format, options can also be a string, such as' utf8'.

The first parameter of the callback function is the possible exception object, and the second parameter is the data read from the file, and the possible data type is string or Buffer. Such as

Fs.readFile ('README.md',' utf8', (err, data) = > {if (err) {console.log ('read failed');} else {console.log (data);}})

The synchronous version of this method is fs.readFileSync (path [, options]).

In addition, there is an alternative to this method, fs.read, please refer to fs.read. It is a general method to read files when using fs.open to open files, and the granularity of control over the reading process is finer. This method is generally used when reading the same file frequently.

15. Fs.rename (oldPath, newPath, callback)

Renames the file specified by oldPath to the file specified by newPath, or overwrites it if it already exists.

The callback function receives only the exception objects that may be thrown.

Its synchronous version is fs.renameSync (oldPath, newPath).

16. Fs.stat (path [, options], callback)

Gets the details of a file.

Such as

Fs.stat ('README.md', {bigint: true}, function (err, stats) {console.log (stats.isDirectory ()); console.log (stats);})

Options only supports the parameter bigint, which means that the returned stats object is of type bigint rather than the usual number type. For the results of the above operations, please refer to the fs.Stats class.

Its synchronous version is fs.statSync (path [, options], callback).

17. Fs.writeFile (file, data [, options], callback)

Similar to fs.readFile, this method is the writing method of the file.

The file parameter is the path to the file to write, or a file descriptor.

Data is the data to be written, support, and so on.

Options supports three parameters: encoding, the default value is' utf8';mode, the permission type, the default value is 0o666 position flag, the opening mode, and the default value is w.

The callback function supports only one parameter, that is, the exception object that may be thrown.

The synchronous version of this method is fs.writeFileSync (file, data [, options]).

When using fs.open to open a file, fs.write is generally used for data writing, please refer to fs.write. This method can accurately control the writing position, and can write data continuously.

Summary

The above list is only some of the commonly used api in the fs module, and there are many other purpose interfaces in the official documents. If you are interested, please refer to the nodejs Chinese website-fs module.

If you need to use the above api in the async function, you can call the encapsulated version of promise provided by the fs module, such as:

Let fsPromises = require ('fs'). Promises;// or let fsPromises = require (' fs/promises'); / / or let fs = require ('fs'); let fsPromises = fs.promises;fsPromise.readFile (). Then ((err, data) = > {.}) async function print (path) {try {let data = await fsPromise.readFile (path,' utf8'); console.log (data) / / read successfully, output data} catch (e = > {... / read failed})} at this point, the study on "which module of nodejs can manipulate files" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report