小程序开放平台

文档中心
基础
界面
网络
数据缓存
媒体
位置
开放接口
设备
XHSML
性能
文件
removeSavedFile
openDocument
getFileSystemManager
FileSystemManager
FileSystemManager
access
accessSync
appendFile
appendFileSync
copyFile
copyFileSync
getSavedFileList
getFileInfo
mkdir
mkdirSync
readdir
mkdirSync
readdir
readdirSync
rmdir
rmdirSync
rename
renameSync
readFile
readFileSync
removeSavedFile
stat
statSync
saveFile
saveFileSync
truncate
truncateSync
unlink
unlinkSync
unzip
writeFile
writeFileSync
Stats
FileStats
数据分析
画布

fs.readFile

开发
>
JS API
>
文件
>
FileSystemManager
>
readFile
>
更新时间:2025-08-08 17:17:07

📌 从基础库 3.125.4 版本开始支持

功能描述

读取本地文件内容。单个文件大小上限为100M。

参数

Object object

属性
类型
默认值
必填
说明
filePathstring要读取的文件的路径 (本地路径)
encodingstring指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容。
小红书仅支持以下编码格式
utf-8
utf8
binary
positionnumber从文件指定位置开始读,如果不指定,则从文件头开始读。读取的范围应该是左闭右开区间 [position, position+length)。有效范围:0, fileLength - 1。单位:byte
lengthnumber指定文件的长度,如果不指定,则读到文件末尾。有效范围:1, fileLength。单位:byte
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

object.success 回调参数

Object res

属性
类型
说明
datastring/ArrayBuffer文件内容

支持的编码类型

✅ 小红书平台支持:

  • utf-8 / utf8
  • binary

❌ 不支持的编码:

ascii/hex/ucs2/ucs-2/utf16le/utf-16le/latin1

示例代码

javascript
const fs = xhs.getFileSystemManager()

// 异步接口
fs.readFile({
  filePath: `${xhs.env.USER_DATA_PATH}/hello.txt`,
  encoding: 'utf8', 
  position: 0,
  success(res) {
    console.log(res.data)
  },
  fail(res) {
    console.error(res)
  }
})

// 同步接口
try {
  const res = fs.readFileSync(
    `${xhs.env.USER_DATA_PATH}/hello.txt`,
    'utf8',  
    0
  )
  console.log(res)
} catch(e) {
  console.error(e)
}