In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
This article will explain in detail how to operate the fs file system in nodeJS. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Overview
The file iMap O is provided by a standard POSIX function that is simply encapsulated. Use this module through require ('fs'). All methods come in the form of asynchronism and synchronization.
The asynchronous form always takes the completion callback as its last parameter. The parameters passed to complete the callback depend on the specific method, but the first parameter is always left to the exception. If the operation completes successfully, the first parameter will be null or undefined
/ / Asynchronous example var fs = require ('fs'); fs.unlink (' / tmp/hello', function (err) {if (err) throw err; console.log ('successfully deleted / tmp/hello');})
When the synchronous form is used, any exception is thrown immediately. You can use try/catch to handle exceptions or make them bubble up
/ / synchronization example var fs = require ('fs'); fs.unlinkSync (' / tmp/hello'); console.log ('successfully deleted / tmp/hello')
Asynchronous methods do not guarantee the order of execution. So the following example is error-prone
Fs.rename ('/ tmp/hello','/ tmp/world', function (err) {if (err) throw err; console.log ('renamed complete');}); fs.stat (' / tmp/world', function (err, stats) {if (err) throw err; console.log ('stats: ${JSON.stringify (stats)}');})
Fs.stat may be executed before fs.rename. The right way is to chain up the callback.
Fs.rename ('/ tmp/hello','/ tmp/world', function (err) {if (err) throw err; fs.stat ('/ tmp/world', function (err, stats) {if (err) throw err; console.log ('stats: ${JSON.stringify (stats)}');})
Developers are recommended to use asynchronous versions of these functions. Synchronous versions block the entire process until they are complete (stop all connections)
Underlying operation
1. Open the file [fs.open (path, flags [, mode], callback)]
The parameters are as follows:
Path | flags | mode sets the file mode (permissions and sticky bits), but is valid only if the file is created. The default is 0666 and callback is readable and writable. This callback has two parameters (err error, fd file ID, similar to timer ID).
Flags can be:
'r'-opens the file in read mode. An exception occurs if the file does not exist.' Ringing'- opens the file in read-write mode. An exception occurs if the file does not exist.' Rs+'-opens the file in synchronous read-write mode. Command the operating system to bypass the local file system cache.' W'- opens the file in write mode. The file is created (if the file does not exist) or truncated (if the file exists).' Wx'-similar to 'wicked, but failed if path exists.' Open the file in read-write mode. The file is created (if the file does not exist) or truncated (if the file exists).' Wx+'-similar to 'wicked destroy, but fails if path is present.' A'- opens the file in append mode. If the file does not exist, it will be created.' Ax'-similar to 'asides, but fails if path exists.' Open the file in read and append mode. If the file does not exist, it will be created.' Ax+'-similar to 'ajar', but fails if path exists.
[note] using the 'rs+' mode does not cause fs.open () to enter synchronous blocking calls. If that's what you want, you should use fs.openSync ()
Var fs = require ('fs'); fs.open (' a. Txt recording grammar) {console.log (err); / / null console.log (fs); / / 3}) var fs = require ('fs') Fs.open (err,fs) {/ * {Error: ENOENT: no such file or directory, open' D:\ project\ b.txt' at Error (native) errno:-4058, code: 'ENOENT', syscall:' open', path:'D:\\ project\\ b.txt'} * / console.log (err); console.log (fs); / / undefined})
The second parameter fd in the callback function of the file represents the file ID, which is similar to the timer ID and is used to identify the file and increases with the order in which the file is opened.
Var fs = require ('fs'); fs.open (' 1. Txt) (err,fs) {console.log (fs); / / 3}) fs.open ('2.txt) err,fs) {console.log (fs); / / 4})
[fs.openSync (path, flags [, mode])]
A synchronous version of fs.open (). Returns an integer that represents a file descriptor
Var fs = require ('fs'); var result = fs.openSync (' 1.txt'); console.log (result); / / 3
2. Read the file [fs.read (fd, buffer, offset, length, position, callback)]
The parameters are as follows:
The file descriptor buffer returned by fd through the fs.open () method will be written to the offset in bufferoffset buffer length specifies the number of bytes to read (integer) position specifies the location to start reading from the file (integer). If position is null, the callback callback takes three parameters (err, bytesRead, buffer) to read the data from the current file location. Err is the error message, bytesRead indicates the number of bytes read, and buffer is the buffer object.
Because the contents of the file are read into the buffer object using the read () method, you need to prepare a buffer object in advance
Var fs = require ('fs'); fs.open (' 1. Txt) {if (err) {console.log ('file opening failed');} else {var bf = Buffer.alloc (5); fs.read (fd,bf,0,3,null,function (err,len,buffer) {console.log (err); / / null console.log (len) / / 3 console.log (buffer); / /})})
[fs.readSync (fd, buffer, offset, length, position)]
A synchronized version of fs.read () that returns the number of bytesRead
Var fs = require ('fs'); var fd = fs.openSync; var bf = Buffer.alloc (5); var result = fs.readSync (fd,bf,0,3,null); console.log (result); / / 3
3. Write to the file [fs.write (fd, buffer, offset, length [, position], callback)]
The parameters are as follows
The fd file identifies buffer | the starting position of the data to be written from the buffer to the offset buffer object in the file length length is an integer that specifies the number of bytes to write position specifies the offset of the location where the data is written from the file. If typeof position! = 'number', the data is written from the current position to the callback callback with three parameters (err, written, buffer), where written specifies how many bytes are written from buffer
[note] it is not safe to use fs.write on the same file multiple times without waiting for a callback. For this situation, fs.createWriteStream is highly recommended
When we want to write to an open file, the mode of opening the file should be read-write mode
Var fs = require ('fs'); fs.open (' 1.txt) {if (err) {console.log ('file opening failed');} else {var bf = Buffer.from ('test'); fs.write (fd,bf,0,3,null,function (err,len,buffer) {console.log (err); / / null console.log (len) / / 3 console.log (buffer); / /})})
[fs.write (fd, data [, position [, encoding]], callback)]
This method writes data to the file specified by fd. If data is not an instance of Buffer, the value is cast to a string
Unlike writing to buffer, the entire string of this method must be written. A substring cannot be specified because the byte offset of the resulting data may be different from the offset of the string
The fd file identifies data | the offset of the position pointing to the location where the data is written from the file to be written to the file from the string or buffer. If typeof position! = 'number', the data is written from the current position to the string-encoded callback callback expected by encoding, which has three parameters (err, written, str), where written specifies how many bytes var fs = require (' fs') was written from str; fs.open ('1.txtencoding) {if (err) {console.log (' file opening failed') } else {fs.write (fd,'12345',function (err,len,str) {console.log (err); / / null console.log (len); / / 5 console.log (str); / /})})
[fs.writeSync ()]
A synchronous version of fs.write (). Returns the number of bytes written
Var fs = require ('fs'); var fd = fs.openSync; var bf = Buffer.alloc (5); var result = fs.writeSync (fd,bf,0,3,null); console.log (result); / / 3
4. Close the file [fs.close (fd, callback)]
After a file is manipulated, close the file in time.
The parameters are as follows:
Fd-the file descriptor returned by the fs.open () method. Callback-callback function with no arguments.
Var fs = require ('fs'); fs.open (' 1. Txt) {if (err) {console.log ('file opening failed');} else {fs.close (fd, function (err) {if (err) {console.log (err);} console.log ("file closed successfully") });})
[fs.closeSync (fd)]
Synchronous version of fs.close (fd, callback), which returns undefined
Var fs = require ('fs'); var fd = fs.openSync (' 1.txt'); fs.closeSync (fd); File operation
The previous section introduces some low-level operations, and then we will introduce some more convenient file operations. When using the following methods, you no longer need to open and close the file, you can do it directly.
1. Write to the file
[fs.writeFile (file, data [, options], callback)]
Write data to a file asynchronously, create a new file if the file does not exist, and replace it if the file already exists
The parameters are as follows:
File-the file name or file descriptor. Data-the data to write to the file, which can be a String (string) or Buffer (stream) object. Options-this parameter is an object containing {encoding, mode, flag}. The default code is utf8, the mode is 0666, the flag is the 'w'callback-callback function, and the callback function contains only the error message parameter (err), which is returned when the write fails. Var fs = require (' fs'); var filename = '1.txtplayposition fs.writeFile (filename,'hello',function (err) {console.log (err); / / null})
[fs.writeFileSync (file, data [, options])]
A synchronous version of fs.writeFile (). Return to undefined
Var fs = require ('fs'); var filename =' 1.txtbirthplace fs.writeFileSync (filename,'abc')
2. Append files
[fs.appendFile (filename, data, [options], callback)]
Asynchronously appends data to a file and creates a file if it does not exist. Data can be a string or buffer
The parameters are as follows
File-the file name or file descriptor. Data-the data to write to the file, which can be a String (string) or Buffer (stream) object. Options-this parameter is an object containing {encoding, mode, flag}. The default code is utf8, the mode is 0666, the flag is the 'w'callback-callback function, and the callback function contains only the error message parameter (err), which is returned when the write fails. Var fs = require (' fs'); var filename = '1.txtalternate fs.appendFile (filename,' world',function (err) {console.log (err); / / null})
[fs.appendFileSync (file, data [, options])]
A synchronous version of fs.appendFile (). Return to undefined
Var fs = require ('fs'); var filename =' 1.txtbirthday fs.appendFileSync (filename,' lalala')
3. Read the file
[fs.readFile (file [, options], callback)]
The parameters are as follows
File-file name or file descriptor options-this parameter is an object that contains {encoding, flag}. The default encoding is null, that is, if the character encoding is not specified, the original buffer is returned Flag defaults to the 'r'callback-callback function, which takes two parameters (err,data), where data is the content of the file (buffer object) and err is the error message parameter, which returns var fs = require (' fs') when writing fails; var filename = '1.txt callback fs.readFile (filename,function (err,data) {if (err) {console.log (' file read failed')) } else {console.log (data); / / console.log (data.toString ()); / / 'abc world lalala'}})
[fs.readFileSync (file [, options])]
A synchronized version of fs.readFile. Returns the contents of file
If the encoding option is specified, the function returns a string, otherwise it returns a buffer
Var fs = require ('fs'); var filename =' 1.txtchallenge result = fs.readFileSync (filename); console.log (result); / / console.log (result.toString ()); 'abc world lalala'
4. Delete files
[fs.unlink (path, callback)]
The parameters are as follows:
Path-File path. Callback-callback function with no arguments. Var fs = require ('fs'); var filename =' 1.txtsuccessfulfs.unlink (filename, function (err) {if (err) {return console.log ('deletion failed');} console.log ("deletion successful");})
[fs.unlinkSync (path)]
Synchronous version of fs.unlink (path, callback). The returned value is undefined.
Var fs = require ('fs'); var filename =' 1.txtbirthday fs.unlink (filename)
5. Rename
[fs.rename (oldPath, newPath, callback)]
The parameters are as follows:
OldPath | newPath | callback callback has only one possible exception parameter var fs = require ('fs'); var filename =' a. Txt callback: fs.rename (filename,'2.new.txt',function (err) {console.log (err); / / null})
[fs.renameSync (oldPath, newPath)]
Synchronous version of fs.rename (oldPath, newPath, callback), which returns undefined
Var fs = require ('fs'); var filename =' 2.new.txtalternate result = fs.renameSync (filename,'a.txt')
6. File information
[fs.stat (path, callback)]
After fs.stat () is executed, an instance of the stats class is returned to its callback function. The relevant attributes of the file can be determined by the providing method in the stats class
The parameters are as follows:
Path-File path. Callback-callback function with two parameters such as: (err,stats), stats is the fs.Stats object var fs = require ('fs'), and var filename =' a.txtcallat (filename,function (err,stats) {console.log (err)) / / null/* {dev: 223576, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: undefined, ino: 7599824371527537, size: 0, blocks: undefined, atime: 2017-06-03T14:18:15.370Z, mtime: 2017-06-03T14:18:15.370Z, ctime: 2017-06-03T16:32:05.776Z, birthtime: 2017-06-03T14:18:15.370Z} * / console.log (stats);})
The methods in the stats class are
Stats.isFile () returns true if it is a file, false otherwise. Stats.isDirectory () returns true if it is a directory, false otherwise. Stats.isBlockDevice () returns true if it is a block device, false otherwise. Stats.isCharacterDevice () returns true if it is a character device, false otherwise. Stats.isSymbolicLink () returns true if it is a soft link, false otherwise. Stats.isFIFO () returns true if it is FIFO, otherwise it returns false. FIFO is a special type of command pipeline in UNIX. Stats.isSocket () returns true if it is Socket, false otherwise. Var fs = require ('fs'); var filename =' a.txtbirthday fs.stat (filename,function (err,stats) {console.log (stats.isFile ()); / / true})
[fs.statSync (path)]
A synchronized version of the fs.stat (path, callback) method that returns an instance of fs.Stats
Var fs = require ('fs'); var filename =' a.txtmisting result = fs.statSync (filename) / * {dev: 223576, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: undefined, ino: 7599824371527537, size: 0, blocks: undefined, atime: 2017-06-03T14:18:15.370Z, mtime: 2017-06-03T14:18:15.370Z, ctime: 2017-06-03T16:32:05.776Z, birthtime: 2017-06-03T14:18:15.370Z} * / console.log (result)
7. Monitoring
[fs.watch (filename [, options] [, listener])]
This method is used to monitor changes in filename, which can be a file or a directory. The returned object is a fs.FSWatcher
The parameters are as follows
Filename | options | optional parameter. If options is a string, it specifies encoding. Otherwise, options should pass in an object to persistent to indicate whether the process should continue to run if the file is being monitored. The default is true recursive to indicate whether all subdirectories should be monitored, or just the current directory. Applies when a directory is specified and only on supported platforms. The default is false encoding to specify the character encoding of the file name that is passed to the listener. By default, the 'utf8'listener callback function takes two parameters (eventType, filename). EventType can be' rename' or 'change',filename is the name of the file that triggered the event
The filename parameter provided in the callback is only supported on Linux and Windows systems. Even on supported platforms, filename is not guaranteed to provide. Therefore, do not assume that the filename parameter is always provided in the callback. If it is empty, some fallback logic is required.
Fs.watch ('somedir', (eventType, filename) = > {console.log (`event type is: ${eventType} `); if (filename) {console.log (file name provided: ${filename}`);} else {console.log (' file name not provided';}}); var fs = require ('fs'); var filename =' 1.txtpromoteristfs.watch (filename,function (eventType, _ filename) {console.log (eventType)) / / change if (_ filename) {console.log (_ filename + 'changed'); / / '1.txt has changed'} else {console.log ('...');}})
[note] when a file appears or disappears in a directory, 'rename' is also triggered
Directory operation
1. Create
[fs.mkdir (path [, mode], callback)]
The parameters are as follows:
Path-File path. Mode-sets directory permissions, which defaults to 0777. Callback-callback function, which has only one possible exception parameter var fs = require ('fs'); fs.mkdir ('. / 1) console.log (err) {console.log (err); / / null})
[fs.mkdirSync (path [, mode])]
Synchronous version of fs.mkdir (path [, mode], callback), which returns undefined
Var fs = require ('fs'); fs.mkdirSync ('. / 2')
2. Delete
[fs.rmdir (path, callback)]
The parameters are as follows:
Path-File path. Callback-callback function, which has only one possible exception parameter var fs = require ('fs'); fs.rmdir ('. / 1) console.log (err) {console.log (err); / / null})
[fs.rmdirSync (path, callback)]
Synchronous version of fs.rmdir (path, callback), which returns undefined
Var fs = require ('fs'); fs.rmdirSync ('. / 2')
3. Read
[fs.readdir (path [, options], callback)]
The parameters are as follows:
Path | options | the optional options parameter is used to pass in the file name of the callback, which can be a string and specify a character encoding, or an object with a character encoding specified by an encoding attribute. If encoding is set to 'buffer', the returned file name will be passed into encoding as a Buffer object. Default =' utf8'callback callback has two parameters (err, files), where files is not included in the directory'.' And'.' Array of filenames var fs = require ('fs'); fs.readdir ('. /', function (err,data) {console.log (err); / / null/* ['.csslintrc', '.jshintrc', 'a.txtnames,' dist', 'Gruntfile.js',' Gruntfile1.js', 'index.html',' main.js', 'node_modules',' package.json', 'src'] * / console.log (data) }) var fs = require ('fs'); fs.readdir ('. /', function (err,data) {data.forEach (function (item,index,arr) {fs.stat (item,function (err,stats) {if (stats.isFile ()) {console.log ('file:' + item) } if (stats.isDirectory ()) {console.log ('directory:' + item);}})}) / * File: .jshintrc file: .csslintrc directory: dist file: Gruntfile.js file: index.html file: Gruntfile1.js file: main.js file: node_modules file: a.txt file: src * /
[fs.readdirSync (path [, options], callback)]
A synchronized version of fs.readdir (path [, options], callback) that returns a version that does not include'.' And'.' An array of file names of
Var fs = require ('fs'); var result = fs.readdirSync ('. /'); / * ['.csslintrc', '.jshintrc', 'a.txttrees,' dist', 'Gruntfile.js',' Gruntfile1.js', 'index.html',' main.js', 'node_modules',' package.json', 'src'] * / console.log (result); traverse the directory
Traversing directories is a common requirement when manipulating files. For example, when writing a program, when you need to find and process all the JS files in a specified directory, you need to traverse the entire directory.
Recursive algorithms are generally used when traversing directories, otherwise it is difficult to write concise code. Recursive algorithms, similar to mathematical induction, solve problems by constantly reducing the size of the problem.
Function factorial (n) {if (n = 1) {return 1;} else {return n * factorial (n-1);}}
The above function is used to calculate the factorial (N!) of N. It can be seen that when N is greater than 1, the problem is reduced to calculating the factorial of N times Nmurl. When N equals 1, the problem reaches the minimum size and does not need to be simplified, so return 1 directly.
The directory is a tree structure, and the depth-first + preorder traversal algorithm is generally used when traversing. Depth first means that after arriving at a node, the child node is traversed first rather than the neighbor node. Preorder traversal means that traversal is completed when you reach a node for the first time, rather than returning to a node for the last time. So when using this traversal method, the traversal order of the following tree is A > B > D > E > C > F.
A /\ B C /\\ D E F
After understanding the necessary algorithms, we can simply implement the following directory traversal function
Function travel (dir, callback) {fs.readdirSync (dir) .forEach (function (file) {var pathname = path.join (dir, file); if (fs.statSync (pathname). IsDirectory ()) {travel (pathname, callback);} else {callback (pathname);}});}
As you can see, this function takes a directory as the starting point for traversal. When you encounter a subdirectory, go through the subdirectories first. When a file is encountered, the absolute path of the file is passed to the callback function. After the callback function gets the file path, it can make a variety of judgments and processing. So suppose you have the following directories
-/ home/user/-foo/ x.js-bar/ y.js z.css
When you iterate through the directory using the following code, the input is as follows
Travel ('/ home/user', function (pathname) {console.log (pathname);});-- / home/user/foo/x.js/home/user/bar/y.js/home/user/z.css
If asynchronous API is used to read directories or file states, the directory traversal function can be a bit complicated to implement, but the principle is exactly the same. The asynchronous version of the travel function is as follows
Function travel (dir, callback, finish) {fs.readdir (dir, function (err, files) {(function next (I) {if (I < files.length) {var pathname = path.join (dir, files [I])) Fs.stat (pathname, function (err, stats) {if (stats.isDirectory ()) {travel (pathname, callback, function () {next (I + 1);}) } else {callback (pathname, function () {next (I + 1);} else {finish & & finish () }} (0));};} this is the end of the article on "how to operate the fs file system in nodeJS". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.