小程序开放平台

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

fs.readFileSync

开发
>
JS API
>
文件
>
FileSystemManager方法
>
readFileSync
>
更新时间:2025-07-23 11:42:03

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

功能描述

FileSystemManager.readFile 的同步版本

参数

参数
类型
说明
filePathstring要读取的文件的路径 (本地路径)
encodingstring指定读取文件的字符编码(小红书仅支持:utf-8/utf8/binary),不传则返回 ArrayBuffer
positionnumber从文件指定位置开始读(单位:byte),有效范围:0, fileLength - 1
lengthnumber指定读取长度(单位:byte),有效范围:1, fileLength

encoding 支持值

说明
utf-8UTF-8 编码
utf8UTF-8 编码
binary二进制

返回值

string|ArrayBuffer

文件内容

示例代码

javascript
const fs = xhs.getFileSystemManager()

try {
  // 读取UTF-8文本
  const text = fs.readFileSync(
    `${xhs.env.USER_DATA_PATH}/hello.txt`, 
    'utf8', 
    0        
  )
  console.log(text)

  // 读取二进制数据
  const buffer = fs.readFileSync(
    `${xhs.env.USER_DATA_PATH}/image.png`,
    'binary'
  )
  console.log(buffer)
} catch(e) {
  console.error('读取文件失败:', e)
}