小程序开放平台

文档中心
基础
界面
网络
数据缓存
媒体
位置
开放接口
设备
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.writeFileSync

开发
>
JS API
>
文件
>
FileSystemManager
>
writeFileSync
>
更新时间:2025-07-23 11:42:09

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

功能描述

FileSystemManager.writeFile
的同步版本,用于写入文件内容

参数

名称
类型
必填
说明
filePathstring目标文件路径(本地路径)
datastring/ArrayBuffer要写入的内容(文本或二进制)
encodingstring字符编码(小红书仅支持部分编码)

encoding的合法值

说明
utf-8
UTF-8 编码
utf8
UTF-8 编码
binary
二进制格式

示例代码

javascript
const fs = xhs.getFileSystemManager()
fs.writeFile({
  filePath: `${xhs.env.USER_DATA_PATH}/hello.txt`,
  data: 'some text or arrayBuffer',
  encoding: 'utf8',
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

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