Node.js如何使用fs.readFile()方法?用法详细示例

2021年3月29日18:18:56 发表评论 2,100 次浏览

fs.readFile()方法是用于读取文件的内置方法。此方法将整个文件读入缓冲区。要加载fs模块, 我们使用require()方法。例如:var fs = require('fs');

语法如下:

fs.readFile( filename, encoding, callback_function )

参数:该方法接受上述和以下所述的三个参数:

  • 文档名称:它保存要读取的文件名或完整路径(如果存储在其他位置)。
  • encoding:它保存文件的编码。其默认值为‘utf8’.
  • callback_function:这是在读取文件后调用的回调函数。它带有两个参数:
    • err:如果发生任何错误。
    • data:文件内容。

返回值:它返回存储在文件中的内容/数据或错误(如果有)。

以下示例说明了Node.js中的fs.readFile()方法:

范例1:

// Node.js program to demonstrate
// the fs.readFile() method
  
// Include fs module
var fs = require( 'fs' );
  
// Use fs.readFile() method to read the file
fs.readFile( 'Demo.txt' , 'utf8' , function (err, data){
      
     // Display the file content
     console.log(data);
});
  
console.log( 'readFile called' );

输出如下:

readFile called
undefined

说明:输出未定义, 表示文件为空。它开始读取文件并同时执行代码。读取文件后将调用该函数, 同时打印" readFile named"语句, 然后打印文件的内容。

范例2:

// Node.js program to demonstrate
// the fs.readFile() method
  
// Include fs module
var fs = require( 'fs' );
  
// Use fs.readFile() method to read the file
fs.readFile( 'demo.txt' , (err, data) => {
     console.log(data);
  })

输出如下:

undefined

参考: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: