Node.js provides a variety of apis for reading files
fs.readFile
Fs.readfile (path[, options], callback) is the most common method for reading a file asynchronously
const fs = require('fs');
fs.readFile('./test.txt'.(err, data) = > {
if (err) throw err;
console.log(data);
});
Copy the code
The callback passes in two arguments (err, data), where data is the contents of the file, and if options is a string, it specifies the character encoding:
fs.readFile('./test.txt'.'utf8', callback);
Copy the code
Options can be set to an object
fs.readFile('./test.txt', { encoding: 'utf8'.flag: 'r' }, callback);
Copy the code
Fs. open, fs.read, fs.close
Fs.readfile is fairly simple to use and should be used most times when reading small files, but fs.readfile () reads the entire file. If you want to read portions of the file exactly, Node.js also provides operations similar to C language fopen, fgeTC, and fclose
There are also three steps to reading a file in Node.js
- Fs.open () : Allocates (opens) the file descriptor
- Fs.read () : reads the file contents
- Fs.close () : Closes the file descriptor
- Path File path (can also be Buffer, URL)
- Flags Indicates the file flag bit. The default value r (short for read) indicates that the file is used for reading
- Mode File mode. Default value: 0o666 (rw-) Read-write
- callback
- err
- File description assigned by fd
fs.read(fd, [options,] callback)
Fs. read is used to read data from a file descriptor.
- Fd file descriptor
- optionsOptional. Do not use the following default values
- Buffer: Buffer to which data (read from fd) is to be written, a new buffer is requested by default
Buffer.alloc(16384)
- Offset: The offset at which buffer starts writing. The default value is 0
- Length: indicates the number of bytes to be read. The default value is length
buffer.length
- Position: The position from which data is read in the file; If position is null, it reads from the current file location and resets the file location to the last one; If position is an integer, the file location is held. The default value is null
- Buffer: Buffer to which data (read from fd) is to be written, a new buffer is requested by default
- callback
- err
- bytesRead
- buffer
Fs. read(fd, buffer, offset, length, position, callback)
fs.close(fs, callback)
Fs.close is used to close file descriptors. Most operating systems limit the number of file descriptors that can be opened at the same time, so it is important to close the descriptor when the operation is complete. Failure to do so will result in a memory leak that will eventually crash the application
demo
test.txt
0123456789
abcdefghigklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Copy the code
const fs = require('fs');
const promisify = require('util').promisify;
const open = promisify(fs.open);
const read = promisify(fs.read);
const close = promisify(fs.close);
async function test() {
const fd = await open('./test.txt');
const readOptions = {
// buffer: buffer.alloc (26), asynchronous calls can not be set by default, if you want to read bytes into the specified buffer can be specified
position: 11.// The file position is reset after the 11th byte is read
length: 26.// Read 26 bytes
};
const { bytesRead: bytesRead1, buffer: buf1 } = await read(fd, readOptions);
console.log('Number of bytes first read:${bytesRead1}`);
console.log('First reading of data content:${buf1.toString()}`);
// Do not specify position, the file position is held after each read
const { bytesRead: bytesRead2, buffer: buf2 } = await read(fd, { length: 1 });
console.log('read the second time from the reset position of the file${bytesRead2}Byte content:${buf2.toString()}`);
const { bytesRead: bytesRead3, buffer: buf3 } = await read(fd, { length: 1 });
console.log('a third read from the current location of the file${bytesRead3}Byte content:${buf3.toString()}`);
await close(fd);
console.log('file descriptor${fd}Closed `);
}
test();
Copy the code
First read bytes: 26 first read data content: abcdefghigklmnopqrstuvwxyz second 1 byte read from the file after the reset position content: 0 1 byte read from the file the current position for the third time: 1 file descriptor 20 has been closedCopy the code
- The program reads from byte 11 for the first time
test.txt
Contents, read a total of 26 bytes - The first read sets the position property, and the file pointer position is reset to 0 after the read is complete
- The second read without setting position after reading a byte, the file position stays at 1
- The third read starts directly from file location 1
Do not use this method to read files unless you want precise control. Manual control of buffers and file location Pointers is prone to all kinds of unexpected situations
fs.createReadStream
Create fs.createreadStream (path[, options])
- path
- Options:
- Fd: If fd is specified, ReadStream ignores the path argument and uses the specified file descriptor (without triggering the open event again).
- AutoClose: Default: true: indicates whether the file descriptor is automatically closed when the file is read or an exception occurs
- Start: indicates the position to start reading
- “End” : indicates the end reading position
- HighWaterMark: Default value: 64 x 1024. Common readable streams are usually 16K
Each state of the stream will have the corresponding event thrown, or read the test.txt file used above
const fs = require('fs');
const rs = fs.createReadStream('./test.txt', { start: 11.end: 36 });
rs.on('open'.fd= > {
console.log('file descriptor${fd}Allocated `);
});
rs.on('ready'.() = > {
console.log('File ready');
});
rs.on('data'.chunk= > {
console.log('Read file data :', chunk.toString());
});
rs.on('end'.() = > {
console.log('File read completed');
});
rs.on('close'.() = > {
console.log('File closed');
});
rs.on('error'.(err) = > {
console.log('File reading exception occurred :', err.stack);
});
Copy the code
20 allocated file descriptor file is ready to read file data: abcdefghigklmnopqrstuvwxyz file read complete file has been closedCopy the code
Can read the detailed operation flow reference: can read flow www.yuque.com/sunluyong/n…
The minimalist Node. Js introductory tutorial: www.yuque.com/sunluyong/n…
In this paper, a better reading experience: www.yuque.com/sunluyong/n…