Article directory
fs filesystem module
What is the fs filesystem module?
The fs module is an official module provided by Node.js for manipulating files. It provides a series of methods and properties to meet the user's operation requirements for files.
E.g:
- fs.readFile() method, used to read the contents of the specified file
- fs.writeFile() method, used to write content to the specified file
If you want to use the fs module to manipulate files in JavaScript code, you need to import it first in the following way:
const fs = require('fs');
Read the contents of the specified file
Syntax of fs.readFile()
Use the fs.readFile() method to read the contents of the specified file. The syntax is as follows:
Parameter interpretation:
- Parameter 1: Required parameter, string, indicating the path of the file.
- Parameter 2: An optional parameter, indicating what encoding format to read the file in.
- Parameter 3: Required parameter. After the file is read, the read result will be obtained through the callback function.
E.g:
// 1. 导入 fs 模块,来操作文件
const fs = require('fs')
// 2. 调用 fs.readFile() 方法读取文件
// 参数1:读取文件的存放路径
// 参数2:读取文件时候采用的编码格式,一般默认指定 utf8
// 参数3:回调函数,拿到读取失败和成功的结果 err dataStr
fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
// 2.1 打印失败的结果
// 如果读取成功,则 err 的值为 null
// 如果读取失败,则 err 的值为 错误对象,dataStr 的值为 undefined
console.log(err)
console.log('-------')
// 2.2 打印成功的结果
console.log(dataStr)
})
result:
[Error: ENOENT: no such file or directory, open '11.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'files\\11.txt'
}
-------
undefined
Note: This callback function has two parameters:
- err: returned an error object
- dataStr: returns a successful object
If the read is successful, the value of err is null
If the read fails, the value of err is the error object, and the value of dataStr is undefined
Determine whether the file was read successfully
const fs = require('fs')
fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
if (err) {
return console.log('读取文件失败!' + err.message)
}
console.log('读取文件成功!' + dataStr)
})
write content to the specified file
Syntax of fs.writeFile()
Using the fs.writeFile() method, you can write content to the specified file. The syntax format is as follows:
Parameter interpretation:
- Parameter 1: Required parameter, a string of file path needs to be specified, indicating the storage path of the file.
- Parameter 2: Required parameter, indicating the content to be written.
- Parameter 3: An optional parameter, indicating the format to write the file content in. The default value is utf8.
- Parameter 4: Required parameter, the callback function after the file writing is completed.
Notice:
- The fs.writeFile() method can only be used to create a file, not a path
- Repeatedly calling fs.writeFile() to write to the same file, the newly written content will overwrite the previous old content
E.g:
// 1. 导入 fs 文件系统模块
const fs = require('fs')
// 2. 调用 fs.writeFile() 方法,写入文件的内容
// 参数1:表示文件的存放路径
// 参数2:表示要写入的内容
// 参数3:回调函数
fs.writeFile('./files/3.txt', 'ok123', function(err) {
// 2.1 如果文件写入成功,则 err 的值等于 null
// 2.2 如果文件写入失败,则 err 的值等于一个 错误对象
console.log(err)
})
There will be a formal parameter err in the callback function:
if the file is successfully written, the value of err is equal to null;
if the file writing fails, the value of err is equal to an error object
Determine whether the file was written successfully
// 1. 导入 fs 文件系统模块
const fs = require('fs')
// 2. 调用 fs.writeFile() 方法,写入文件的内容
// 参数1:表示文件的存放路径
// 参数2:表示要写入的内容
// 参数3:回调函数
fs.writeFile('./files/3.txt', 'ok123', function(err) {
// 2.1 如果文件写入成功,则 err 的值等于 null
// 2.2 如果文件写入失败,则 err 的值等于一个 错误对象
// console.log(err)
if (err) {
return console.log('文件写入失败!' + err.message)
}
console.log('文件写入成功!')
})
fs module - the problem of dynamic splicing of paths
When using the fs module to manipulate files, if the provided operation path is a relative path starting with ./ or .../ , the problem of dynamic path splicing error is easy to occur.
Reason: When the code is running, it will dynamically splicing out the full path of the operated file based on the directory where the node command is executed. That is to say, if you are in the directory where the current file is located and use the node command, there will be no dynamic splicing error at this time, but if it is not in the directory where your current file is located, the path will definitely be missing during splicing.
Solution one
Solution: When using the fs module to manipulate files, provide the complete path directly , and do not provide the relative path starting with ./ or .../, so as to prevent the problem of dynamic path splicing.
Disadvantages:
very poor portability, not conducive to maintenance
E.g:
const fs = require('fs')
// 出现路径拼接错误的问题,是因为提供了 ./ 或 ../ 开头的相对路径
// 如果要解决这个问题,可以直接提供一个完整的文件存放路径就行
/* fs.readFile('./files/1.txt', 'utf8', function(err, dataStr) {
if (err) {
return console.log('读取文件失败!' + err.message)
}
console.log('读取文件成功!' + dataStr)
}) */
//解决办法
fs.readFile('C:\\Users\\escook\\Desktop\\code\\files\\1.txt', 'utf8', function(err, dataStr) {
if (err) {
return console.log('读取文件失败!' + err.message)
}
console.log('读取文件成功!' + dataStr)
})
Note: In the path in the string, once there is a \, it should be followed by a \, because \ is the meaning of the escape character, and \ only means
if the path in the string is /, it does not matter
Solution two
Use __dirname to indicate the path
__dirname indicates the directory where the current file is located
fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, dataStr) {
if (err) {
return console.log('读取文件失败!' + err.message)
}
console.log('读取文件成功!' + dataStr)
})