chencl1986/Blog

Nodejs教程03:File System

chencl1986 opened this issue · 0 comments

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

File System

File System是Nodejs中用来操作文件的库,可以通过const fs = require('fs')引用。

常用的方法有异步文件读取fs.readFile、异步文件写入fs.writeFile、同步文件读取fs.readFileSync、同步文件写入fs.writeFileSync。由于同步操作可能会造成阻塞,通常建议使用异步操作避免该问题。

fs.writeFile

示例代码:/lesson03/server.js

https://nodejs.org/dist/latest-v11.x/docs/api/fs.html#fs_fs_writefile_file_data_options_callback

fs.writeFile可向文件写入信息,若文件不存在会自动创建。

fs.writeFile('./test.txt', 'test', (error) => {
  if (error) {
    console.log('文件写入失败', error)
  } else {
    console.log('文件写入成功')
  }
})

fs.writeFile的主要参数:

  1. 第一个参数为写入的文件路径

  2. 第二个参数为写入内容(可为<string> | <Buffer> | <TypedArray> | <DataView>)

  3. 第三个参数为回调函数,传入数据为error对象,其为null时表示成功。

fs.readFile

示例代码:/lesson03/server.js

https://nodejs.org/dist/latest-v11.x/docs/api/fs.html#fs_fs_readfile_path_options_callback

fs.readFile用来读取文件。

fs.readFile('./test.txt', (error, data) => {
  if (error) {
    console.log('文件读取失败', error)
  } else {
    // 此处因确定读取到的数据是字符串,可以直接用toString方法将Buffer转为字符串。
    // 若是需要传输给浏览器可以直接用Buffer,机器之间通信是直接用Buffer数据。
    console.log('文件读取成功', data.toString())
  }
})

fs.readFile主要参数:

  1. 第一个参数为读取的文件路径

  2. 第二个参数为回调函数。回调函数传入第一个参数为error对象,其为null时表示成功,第二个为数据,可为<string> | <Buffer>。