小程序开放平台

文档中心
暂无目录

fs.truncate

更新时间:2025-07-23 11:41:24

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

功能描述

对文件内容进行截断操作

参数

Object object

属性
类型
默认值
必填
说明
filePathstring要截断的文件路径 (本地路径)
lengthnumber0截断位置(单位:字节)。
- 小于文件长度:保留前 length 字节
- 大于文件长度:扩展文件并用空字节('\0')填充
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数

示例代码

javascript
const fs = xhs.getFileSystemManager()

// 异步截断文件
fs.truncate({
  filePath: `${xhs.env.USER_DATA_PATH}/hello.txt`,
  length: 10, // 保留前10字节
  success(res) {
    console.log('文件截断成功')
  },
  fail(res) {
    console.error('文件截断失败:', res)
  }
})

// 同步截断(从基础库3.125.4开始支持)
try {
  fs.truncateSync(
    `${xhs.env.USER_DATA_PATH}/hello.txt`, 
    10 // 保留前10字节
  )
  console.log('同步截断成功')
} catch(e) {
  console.error('同步截断失败:', e)
}
该文档是否对您有帮助?