The fs module is officially provided by Node.js and is used to operate folders. It provides a series of methods and attributes to meet users' requirements for file operation
For example:
·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 operate the file in JavaScript code, you need to import it first in the following way:
const fs=require('fs')
Syntax format of fs. readFile():
fs.readFile(path[,options],callback)
Parameter interpretation:
Path: file path, required parameter, string
Options: What encoding format is used to read the file? Optional parameters
Callback: After reading the file, get the reading result through the callback function. Required parameter
// 1.导入fs模块来操作文件 const fs=require('fs') // 2.调用fs.readFile(path[,options],callback)方法读取文件 // path:文件存放路径 // options:读取文件时采用的编码格式,一般默认指定utf8 // callback:回调函数,拿到读取失败和成功的结果,err datastr fs.readFile('1.js','utf8',function(err,datastr){ // 打印失败的结果 console.log(err) console.log('--------------') // 打印成功的结果 console.log(datastr) })