1. What is a fs file system module
[explanation]: the fs file system module is node JS is an official module for operating files. It provides a series of methods and attributes to meet the basic needs of users for file operation.
[basic usage]:
- Import directly after installing node
const fs = require ('fs')
2. Reads the contents of the specified file
1,fs. Syntax format of readfile()
[syntax]:
fs.readFile(path, [,options], callback)
[parameter interpretation]:
- Parameter 1: required parameter, indicating the path to read the file
- Parameter 2: optional parameter, indicating the optional parameter, indicating the encoding method to read the file
- Parameter 3: required parameter, callback function, to obtain the file content through the callback function
2,fs.readFile() reads the contents of the file
[code example]:
// 1. Import fs module const fs = require('fs'); // 2. Use FS Reads the contents of the file specified by files() /** * Parameter 1: read file storage path * Parameter 2: the encoding format used when reading files * Parameter 3: callback function. Parameter 1 indicates the result of reading failure and parameter 2 indicates the result of reading success */ fs.readFile('./files/11.txt', 'utf-8', function (err, dataStr) { // When the file information is read successfully, the return value of err is null console.log(err); console.log('------------------'); console.log(dataStr); })
3. Judge whether the file is read successfully
[code example]:
// 1. Import fs module const fs = require('fs'); // 2. Use FS The readfiles () method reads the contents of the specified file /** * Parameter 1: read file storage path * Parameter 2: the encoding format used when reading files * Parameter 3: callback function. Parameter 1 indicates the result of reading failure and parameter 2 indicates the result of reading success */ fs.readFile('./files/11.txt', 'utf-8', function (err, dataStr) { if (err) { // Failed to read the file. Error message is returned return console.log('Failed to read file!!' + err.message);; } else { // Read the file successfully, print the file information console.log('Read file successfully:'+dataStr); } })
3. Write content to the specified file
1,fs. Syntax format of writefile()
[syntax]:
fs.writeFile(filePath, data, [,option] callback)
[parameter interpretation]:
- Parameter 1: required parameter, specifying the file string path, indicating the storage path of the file
- Parameter 2: required parameter, indicating the content to be written
- Parameter 3: optional parameter, indicating how to write content. The default is utf-8
- Parameter 4: required parameter, indicating the callback function after the file is written.
2,fs.writeFile() write file
[code example]:
// 1. Import fs module const fs = require('fs') // 2. Use FS Writefile() method to write content to the file /** * Parameter 1: path to write information * Parameter 2: content to be written * Parameter 3: callback function * Parameter 4: encoding format. The default is utf-8. It can be omitted */ fs.writeFile('./files/2.txt', 'Zhang San', function (err) { // err returns null if the file is written successfully // If the file write fails, an error object is returned console.log(err); })
3,fs.writeFile() determines whether the write was successful
// 1. Import fs module const fs = require('fs') // 2. Use FS Writefile() method to write content to the file /** * Parameter 1: path to write information * Parameter 2: content to be written * Parameter 3: callback function * Parameter 4: encoding format. The default is utf-8. It can be omitted */ fs.writeFile('./files/2.txt', 'Zhang San', function (err) { // err returns null if the file is written successfully // If the file write fails, an error object is returned if (err) { return console.log('File write failed' + err.message); } else { console.log('File written successfully!!'); } })
4. Comprehensive application of writing and reading files
[demand]:
- Using fs file system module, the score will be txt file, sort out the test data to the score - OK txt file.
- Before sorting out the results The data format in txt file is as follows:
- Little red = 100
- The sorted format is as follows:
- Xiao Hong: 100
[case analysis]:
- Import fs file module
- Read old data in file
- Judge whether the reading is successful
- Data format processing
- Write to new file
[code implementation]:
// 1. Import fs file system module const fs = require("fs"); // 2. Read score information fs.readFile('./files/achievement.txt', 'utf-8', function (err, data) { // Judge whether the score is read successfully if (err) { // Reading failed, error message returned return console.log('Failed to read the score!!' + err.message); } else { // Read succeeded. Return read data // Separate the score data by spaces const arrOld = data.split(' ') // For the separated array, perform string replacement for each item of data arrNew = []; arrOld.forEach(item => { arrNew.push(item.replace('=', ':')) }) // Merge each item in the new array const newStr = arrNew.join('\r\n') // Write new data to file fs.writeFile('./files/newScore.txt', newStr, function (err) { // Determine whether the write is successful if (err) { // Write failed, error message returned return console.log('Failed to write file information!!' + err.message); } else { // Write successful console.log('Write file succeeded!!'); } }) } })
5. fs module path dynamic splicing problem
[problem description]: when using fs module to operate files, if the operation path provided is in/ Or the relative path starting with... / is prone to the problem of path dynamic splicing error.
[reason]: when the code is running, it will dynamically splice the complete path of the operated file according to the directory where the node command is executed.
[solution]:
- When using fs module to operate files, provide the complete path directly and do not provide it/ Or... / to prevent the problem of path dynamic splicing.
const fs = require('fs'); // __ dirname indicates the directory of the current file fs.readFile(__dirname + '/files/11.txt', 'utf-8', function (err, data) { if (err) { return err.message; } else { console.log(data); } })