Skip to content

File

saveFile

TIP

The API usage is as follows: wx.saveFile(Object object)
This API is supported by mini programs, but not by mini games.

TIP

The size limit of local file storage is 10M.

  • Functional description: Save the file locally

TIP

saveFile will move the temporary file, so the tempFilePath passed in after the call is successful will not be available.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    tempFilePathstring-YesThe temporary path of the file to be saved
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    savedFilePathstringThe file path after storage
  • Sample code:

js
  wx.chooseImage({
  success(res) {
    const tempFilePaths = res.tempFilePaths
    wx.saveFile({
      tempFilePath: tempFilePaths[0],
      success(res) {
        const savedFilePath = res.savedFilePath
      }
    })
  }
})

removeSavedFile

TIP

The API usage is as follows: wx.removeSavedFile(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Delete the local cache file.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to be deleted
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
wx.getSavedFileList({
  success(res) {
    if (res.fileList.length > 0) {
      wx.removeSavedFile({
        filePath: res.fileList[0].filePath,
        complete(res) {
          console.log(res)
        }
      })
    }
  }
})

openDocument

TIP

The API usage is as follows: wx.openDocument(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Open a new page to open the document.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesFile path (local path), can be obtained through downloadFile
    fileTypestring-NoFile type, specify the file type to open the file
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    pdfpdf format
  • Sample code:

js
wx.downloadFile({
  // Example url, not real
  url: 'https://example.com/somefile.pdf',
  success(res) {
    const filePath = res.tempFilePath
    wx.openDocument({
      filePath,
      success(res) {
        console.log('Opened document successfully')
      }
    })
  }
})

getSavedFileList

TIP

The API usage is as follows: wx.getSavedFileList(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Get the list of local cache files saved under this applet.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    fileListArray.<Object>File array, each item is a FileItem
  • The structure of res.fileList

    PropertiesTypeDescription
    filePathstringLocal path
    sizenumberLocal file size, in bytes
    createTimenumberThe timestamp when the file is saved, the number of seconds from 1970/01/01 08:00:00 to the current time
  • Sample code:

js
wx.getSavedFileList({
  success(res) {
    console.log(res.fileList)
  }
})

getSavedFilelnfo

TIP

The API usage is as follows: wx.getSavedFileInfo(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Get the file information of the local file. This interface can only be used to obtain files that have been saved locally. If you need to obtain temporary file information, please use wx.getFileInfo() Interface

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesFile path
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    sizenumberFile size, in B
    createTimenumberThe timestamp when the file is saved, the number of seconds from 1970/01/01 08:00:00 to this moment
  • Sample code:

js
wx.getSavedFileList({
  success(res) {
    console.log(res.fileList)
  }
})

getFileInfo

TIP

The API usage is as follows: wx.getFileInfo(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Get the file information.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesLocal file path
    digestAlgorithmstring'md5'NoAlgorithm for calculating file digest
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    md5md5 algorithm
    sha1sha1 algorithm
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    sizenumberLocal file size, in bytes
    digeststringFile digest calculated according to the passed digestAlgorithm
  • Sample code:

js
wx.getFileInfo({
  success(res) {
    console.log(res.size)
    console.log(res.digest)
  }
})

getFileSystemManager

TIP

The API usage is as follows: FileSystemManager wx.getFileSystemManager()

  • Functional description: Get the globally unique file manager
  • Return value: FileSystemManager File Manager.

FileSystemManager

File manager, throughwx.getFileSystemManager obtain.

.access

TIP

The API usage is as follows: FileSystemManager.access(Object object)

  • Functional description: Judge whether the file/directory exists

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    pathstring-YesThe file/directory path to be determined whether it exists.
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory ${path}File/directory does not exist
    bad file descriptorInvalid file descriptor
    permission deniedPermission error, the file is read-only or write-only
    permission denied, cannot access file pathThe target path has no access rights (usr directory)
    not a directoryThe path specified by dirPath is not a directory, which is common when the parent path of the specified write path is a file
    Invalid argumentInvalid parameters, you can check whether length or offset is out of bounds
    directory not emptyThe directory is not empty
    the maximum size of the file storage limit is exceededInsufficient storage space, or the file size exceeds the upper limit (upper limit 100M)
    base64 encode errorCharacter encoding conversion failed (for example, base64 format error)
    data to write is emptyWritten data is empty
    illegal operation on a directoryThis operation cannot be performed on a directory (for example, the specified filePath is an existing directory)
    file already exists ${dirPath}There is already a file or directory with the same name
    value of length is out of rangeThe length passed in is illegal
    value of offset is out of rangeThe offset passed in is illegal
    value of position is out of rangeThe position value is out of bounds
  • Sample code:

js
const fs = wx.getFileSystemManager()
// Determine if the file/directory exists
fs.access({
  path: `${wx.env.USER_DATA_PATH}/hello.txt`, success(res) {
  success(res) {
    // The file exists
    console.log(res)
  }, fail(res) { // File exists.
  fail(res) {
    // File does not exist or other error
    console.error(res)
  }
})

// Synchronization interface
try {
  fs.accessSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
} catch(e) {
  console.error(e)
}

.accessSync

TIP

The API usage is as follows: FileSystemManager.accessSync(string path)

  • Functional description: FileSystemManager.access The synchronous version

  • Parameters and descriptions: string path, The file/directory path to be determined whether it exists.

  • Sample code:

js
const fs = wx.getFileSystemManager()
// Determine if the file/directory exists
fs.access({
  path: `${wx.env.USER_DATA_PATH}/hello.txt`, success(res) {
  success(res) {
    // The file exists
    console.log(res)
  }, fail(res) { // File exists.
  fail(res) {
    // File does not exist or other error
    console.error(res)
  }
})

// Synchronization interface
try {
  fs.accessSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
} catch(e) {
  console.error(e)
}

.appendFile

TIP

The API usage is as follows: FileSystemManager.appendFile(Object object)

  • Functional description: Append content to the end of the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to which the content is to be appended.
    datastring/ArrayBuffer-YesThe text or binary data to be appended.
    encodingstringutf-8NoSpecify the character encoding for writing to the file.
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory ${path}The specified filePath file does not exist
    fail illegal operation on a directory, open "${filePath}"The specified filePath is an existing directory
    fail permission denied, open ${dirPath}The specified filePath path does not have write permission
    fail sdcard not mountedThe specified filePath is an existing directory
  • Sample code:

js
const fs = wx.getFileSystemManager()

fs.appendFile({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  data: 'some text',
  encoding: 'utf8',
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync
try {
  fs.appendFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'some text', 'utf8')
} catch(e) {
  console.error(e)
}

.appendFileSync

TIP

The API usage is as follows: FileSystemManager.appendFileSync(string filePath, string|ArrayBuffer data, string encoding)

  • Functional description: FileSystemManager.appendFile The synchronous version

  • Parameters and descriptions:

    • string filePath: The file path to which the content is to be appended.
    • string|ArrayBuffer data: The text or binary data to be appended.
    • string encoding: Specify the character encoding for writing to the file.
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • Sample code:

js
const fs = wx.getFileSystemManager()

fs.appendFile({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  data: 'some text',
  encoding: 'utf8',
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync
try {
  fs.appendFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'some text', 'utf8')
} catch(e) {
  console.error(e)
}

.close

TIP

The API usage is as follows: FileSystemManager.close(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Close the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
const fs = wx.getFileSystemManager()
// open file
fs.open({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+',
  success(res) {
    // close file
    fs.close({
      fd: res.fd
    })
  }
})

.closeSync

TIP

The API usage is as follows: undefined FileSystemManager.closeSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Synchronously close the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
  • Return value: undefined。

  • Sample code:

js
const fs = wx.getFileSystemManager()
const fd = fs.openSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+'
})

// close file
fs.closeSync({fd: fd})

.copyFile

TIP

The API usage is as follows: FileSystemManager.copyFile(Object object)

  • Functional description: Copy the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    srcPathstring-YesSource file path, can only be ordinary file
    destPathstring-YesDestination file path, supports local path
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
    • object.fail callback function parameter: Object res。
      PropertiesTypeDescription
      errMsgstringError message
  • Legal values

    ValueDescription
    fail permission denied, copyFile ${srcPath} -> ${destPath}Specified destination file path does not have write permission
    fail no such file or directory, copyFile ${srcPath} -> ${destPath}The source file does not exist, or the upper directory of the destination file path does not exist
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.copyFile({
  srcPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  destPath: `${wx.env.USER_DATA_PATH}/hello_copy.txt`
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  fs.copyFileSync(
    `${wx.env.USER_DATA_PATH}/hello.txt`,
    `${wx.env.USER_DATA_PATH}/hello_copy.txt`
  )
} catch(e) {
  console.error(e)
}

.copyFileSync

TIP

The API usage is as follows: FileSystemManager.copyFileSync(string srcPath, string destPath)

  • Functional description: FileSystemManager.copyFile The synchronous version

  • Parameters and descriptions:

    • string srcPath: The source file path, can only be ordinary file.
    • string destPath: Destination file path.
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.copyFile({
  srcPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  destPath: `${wx.env.USER_DATA_PATH}/hello_copy.txt`
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  fs.copyFileSync(
    `${wx.env.USER_DATA_PATH}/hello.txt`,
    `${wx.env.USER_DATA_PATH}/hello_copy.txt`
  )
} catch(e) {
  console.error(e)
}

.getFileInfo

TIP

The API usage is as follows: FileSystemManager.getFileInfo(Object object)

  • Functional description: Get the local temporary file or local cache file information under the applet.
  • Parameters and descriptions: Object object。
    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to read
    digestAlgorithmstringmd5NoAlgorithm for calculating file digest
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
    • Legal values
      ValueDescription
      md5md5 algorithm
      sha1sha1 algorithm
  • object.success callback function parameters: Object res。
    PropertiesTypeDescription
    sizenumberLocal file size, in bytes
    digeststringFile digest calculated according to the passed digestAlgorithm
  • object.fail callback function parameter: Object res。
    PropertiesTypeDescription
    errMsgstringError message
  • Legal values
    ValueDescription
    fail file not existThe specified filePath cannot find the file
    no such file or directory ${path}The file/directory does not exist, or the parent directory of the target file path does not exist
    Input/output errorThe input and output streams are not available
    permission deniedPermission error, the file is read-only or write-only
    Path permission deniedThe passed path has no permissions
    not a directoryThe path specified by dirPath is not a directory, which is common when the parent path of the specified write path is a file
    Invalid argumentInvalid parameters, you can check whether length or offset is out of bounds
    excced max concurrent fd limitThe number of fds has reached the upper limit

.fstat

TIP

The API usage is as follows: FileSystemManager.fstat(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Get the status information of the file.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    statsstatsStats object, containing the status information of the file.
  • Sample code:

js
const fs = wx.getFileSystemManager()
// open files
fs.open({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+',
  success(res) {
    // get information
    fs.fstat({
      fd: res.fd,
      success(res) {
        console.log(res.stats)
      }
    })
  }
})

.fstatSync

TIP

The API usage is as follows: Stats FileSystemManager.fstatSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Synchronously get the status information of the file.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
  • Return value: Stats, Stats object, containing the status information of the file.

  • Sample code:

js
const fs = wx.getFileSystemManager()
const fd = fs.openSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+'
})
const stats = fs.fstatSync({fd: fd})
console.log(stats)

.ftruncate

TIP

The API usage is as follows: FileSystemManager.ftruncate(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Truncate the file contents.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    lengthnumber-YesTruncation position, default 0. If length is less than the file length (bytes), only the first length bytes will be retained in the file, and the rest will be deleted; if length is greater than the file length, it will be extended, and the extended part will be filled with null bytes ('\0')
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
const fs = wx.getFileSystemManager()
// Open the file
fs.open({
  filePath: ${wx.env.USER_DATA_PATH}/hello.txt,
  flag: 'a+',
      success(res) {
//Truncate the file content.
    fs.ftruncate({
      fd: res.fd,
  length: 10, // Truncate the file starting from the 10th byte
      success(res) {
    console.log(res)
  }
})
  }
})

.ftruncateSync

TIP

The API usage is as follows: undefined FileSystemManager.ftruncateSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Truncate the file contents.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    lengthnumber-YesTruncation position, default 0. If length is less than the file length (bytes), only the first length bytes will be retained in the file, and the rest will be deleted; if length is greater than the file length, it will be extended, and the extended part will be filled with null bytes ('\0')
  • Parameters and descriptions: undefined。

  • Sample code:

js
const fs = wx.getFileSystemManager()
const fd = fs.openSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+'
})
fs.ftruncateSync({
  fd: fd,
  length: 10 // from the 10th byte
})

.getSavedFileList

TIP

The API usage is as follows: FileSystemManager.getSavedFileList(Object object)

  • Functional description: Get the list of local cache files saved under this applet.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    fileListArray.<Object>File array, each item is a FileItem
  • The structure of res.fileList

    PropertiesTypeDescription
    filePathstringLocal path
    sizenumberLocal file size, in bytes
    createTimenumberThe timestamp when the file is saved, the number of seconds from 1970/01/01 08:00:00 to the current time

.mkdir

TIP

The API usage is as follows: FileSystemManager.mkdir(Object object)

  • Functional description: Judge whether the file/directory exists

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    dirPathstring-YesDirectory path to create
    recursivebooleanfalseNoWhether to create the directory after recursively creating the parent directory of the directory. If the corresponding parent directory already exists, it will not be created. If dirPath is a/b/c/d and recursive is true, the a directory will be created, and then the b directory will be created under the a directory, and so on until the d directory under the a/b/c directory is created.
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory ${dirPath}Parent directory does not exist
    fail permission denied, open ${dirPath}The specified filePath path does not have write permission
    fail file already exists ${dirPath}There is a file or directory with the same name
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.mkdir({
  dirPath: `${wx.env.USER_DATA_PATH}/example`,
  recursive: false,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  fs.mkdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
} catch(e) {
  console.error(e)
}

.mkdirSync

TIP

The API usage is as follows: FileSystemManager.mkdirSync(string dirPath, boolean recursive)

  • Functional description: FileSystemManager.mkdir The synchronous version

  • Parameters and descriptions:

    • string dirPath:Directory path to create
    • boolean recursive:Whether to create the directory after recursively creating the parent directory of the directory. If the corresponding parent directory already exists, it will not be created. If dirPath is a/b/c/d and recursive is true, the a directory will be created, and then the b directory will be created under the a directory, and so on until the d directory under the a/b/c directory is created.
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.mkdir({
  dirPath: `${wx.env.USER_DATA_PATH}/example`,
  recursive: false,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  fs.mkdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
} catch(e) {
  console.error(e)
}

.open

TIP

The API usage is as follows: FileSystemManager.open(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Open the file and return the file descriptor

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesFile path (local path)
    flagstringrNoFile system flag, default value: r
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Flag legal value

    Legal valueDescription
    aOpen the file for appending. If the file does not exist, create the file
    axSimilar to 'a', but if the path exists, it will fail
    a+Open the file for reading and appending. If the file does not exist, create the file
    ax+Similar to 'a+', but if the path exists, it will fail
    asOpen the file for appending (in synchronous mode). If the file does not exist, create the file
    as+Open the file for reading and appending (in synchronous mode). If the file does not exist, create the file
    rOpen the file for reading. If the file does not exist, an exception will occur
    r+Open the file for reading and writing. If the file does not exist, an exception will occur
    wOpen the file for writing. Create the file if it does not exist, and truncate it if it exists
    wxSimilar to 'w', but fails if the path exists
    w+Open the file for reading and writing. Create the file if it does not exist, and truncate it if it exists
    wx+Similar to 'w+', but fails if the path exists
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    fdstringFile descriptor
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.open({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+',
  success(res) {
    console.log(res.fd)
  }
})

.openSync

TIP

The API usage is as follows: string FileSystemManager.openSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Synchronously open the file and return the file descriptor.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesFile path (local path)
    flagstringrNoFile system flag, default value: r
  • Flag legal value

    Legal valueDescription
    aOpen the file for appending. If the file does not exist, create the file
    axSimilar to 'a', but if the path exists, it will fail
    a+Open the file for reading and appending. If the file does not exist, create the file
    ax+Similar to 'a+', but if the path exists, it will fail
    asOpen the file for appending (in synchronous mode). If the file does not exist, create the file
    as+Open the file for reading and appending (in synchronous mode). If the file does not exist, create the file
    rOpen the file for reading. If the file does not exist, an exception will occur
    r+Open the file for reading and writing. If the file does not exist, an exception will occur
    wOpen the file for writing. Create the file if it does not exist, and truncate it if it exists
    wxSimilar to 'w', but fails if the path exists
    w+Open the file for reading and writing. Create the file if it does not exist, and truncate it if it exists
    wx+Similar to 'w+', but fails if the path exists
  • Return value: string,File descriptor

  • Sample code:

js
const fs = wx.getFileSystemManager()
const fd = fs.openSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+'
})
console.log(fd)

.read

TIP

The API usage is as follows: FileSystemManager.read(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Read the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    arrayBufferArrayBuffer-YesThe buffer to which the data is written, must be an ArrayBuffer instance
    offsetnumber-NoThe write offset in the buffer, default 6
    lengthnumber-NoThe number of bytes to read from the file, default 6
    positionnumberrNoThe starting position of the file to read, if not passed or null, will read from the current file pointer position, if position is a positive integer, the file pointer position will remain unchanged and read the file from position.
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    bytesReadnumberThe actual number of bytes read
    arrayBufferArrayBufferThe object of the buffer area to be written, that is, the arrayBuffer of the interface input parameter
  • Sample code:

js
const fs = wx.getFileSystemManager()
const ab = new ArrayBuffer(1024)
// open the file
fs.open({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+',
  success(res) {
    // read file to ArrayBuffer
    fs.read({
      fd: res.fd,
      arrayBuffer: ab,
      length: 10,
      success(res) {
        console.log(res)
      }
    })
  }
})

.readSync

TIP

The API usage is as follows: ReadResult FileSystemManager.readSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Read the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    arrayBufferArrayBuffer-YesThe buffer to which the data is written, must be an ArrayBuffer instance
    offsetnumber-NoThe write offset in the buffer, default 6
    lengthnumber-NoThe number of bytes to read from the file, default 6
    positionnumberrNoThe starting position of the file to read, if not passed or null, will read from the current file pointer position, if position is a positive integer, the file pointer position will remain unchanged and read the file from position.
  • Return value: ReadResult File reading results. Through

  • Sample code:

js
const fs = wx.getFileSystemManager()
const ab = new ArrayBuffer(1024)
const fd = fs.openSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+'
})
const res = fs.readSync({
  fd: fd,
  arrayBuffer: ab,
  length: 10
})
console.log(res)

.readCompressedFile

TIP

The API usage is as follows: FileSystemManager.readCompressedFile(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Read the local file contents of the specified compression type.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe path of the file to be read (local user file or code package file)
    compressionAlgorithmstringrYesFile compression type, currently only supports br
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • The legal values

    Legal valueDescription
    brbrotli compressed file
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    dataArrayBufferfile content
  • Sample code:

js
const fs = wx.getFileSystemManager()

// 
fs.readCompressedFile({
  filePath: '${wx.env.USER_DATA_PATH}/hello.br',
  compressionAlgorithm: 'br',
  success(res) {
    console.log(res.data)
  },
  fail(res) {
    console.log('readCompressedFile fail', res)
  }
})

// async api
const data = fs.readCompressedFileSync({
  filePath: '${wx.env.USER_DATA_PATH}/hello.br',
  compressionAlgorithm: 'br',
})
console.log(data)

.readCompressedFileSync

TIP

The API usage is as follows: ArrayBuffer FileSystemManager.readCompressedFileSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Synchronously read the local file contents of the specified compression type.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe path of the file to be read (local user file or code package file)
    compressionAlgorithmstringrYesFile compression type, currently only supports br
  • The legal values

    Legal valueDescription
    brbrotli compressed file
  • Return value: ArrayBuffer,File reading results

  • Sample code:

js
const fs = wx.getFileSystemManager()

// 
fs.readCompressedFile({
  filePath: '${wx.env.USER_DATA_PATH}/hello.br',
  compressionAlgorithm: 'br',
  success(res) {
    console.log(res.data)
  },
  fail(res) {
    console.log('readCompressedFile fail', res)
  }
})

// async api
const data = fs.readCompressedFileSync({
  filePath: '${wx.env.USER_DATA_PATH}/hello.br',
  compressionAlgorithm: 'br',
})
console.log(data)

.readdir

TIP

The API usage is as follows: FileSystemManager.readdir(Object object)

  • Functional description: Read the list of files in the directory

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    dirPathstring-Yesdirectory path to read
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    filesArray.<string>array of file names under the specified directory.
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory ${dirPath}directory does not exist
    fail not a directory ${dirPath}dirPath is not a directory
    fail permission denied, open ${dirPath}the specified filePath path has no read permission
  • Sample code:

TIP

the readdir interface cannot access the file system root path (wxfile://).

js
const fs = wx.getFileSystemManager()
fs.readdir({
  dirPath: `${wx.env.USER_DATA_PATH}/example`,
  success(res) {
    console.log(res.files)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  const res = fs.readdirSync(`${wx.env.USER_DATA_PATH}/example`)
  console.log(res)
} catch(e) {
  console.error(e)
}

.readdirSync

TIP

The API usage is as follows: Array.<string> FileSystemManager.readdirSync(string dirPath)
This API is supported by mini programs, but not by mini games.

  • Functional description: FileSystemManager.readdirThe synchronous version

  • Parameters and descriptions: string dirPath, directory path to read.

  • Return value: Array.<string> files, array of file names under the specified directory.

  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.readdir({
  dirPath: `${wx.env.USER_DATA_PATH}/example`,
  success(res) {
    console.log(res.files)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  const res = fs.readdirSync(`${wx.env.USER_DATA_PATH}/example`)
  console.log(res)
} catch(e) {
  console.error(e)
}

.readFile

TIP

The API usage is as follows: FileSystemManager.readFile(Object object)

  • Functional description: read local file content. The upper limit of a single file size is 100M

  • Parameters and descriptions: Object object

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-Yespath of the file to read
    encodingstring-Nospecify the character encoding of the file to be read. If encoding is not passed, the binary content of the file is read in ArrayBuffer format
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    datastring/ArrayBufferfile content
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory, open ${filePath}the directory where the specified filePath is located does not exist
    fail permission denied, open ${dirPath}the specified filePath path has no read permission
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.readFile({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  encoding: 'utf8',
  position: 0,
  success(res) {
    console.log(res.data)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  const res = fs.readFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'utf8', 0)
  console.log(res)
} catch(e) {
  console.error(e)
}

.readFileSync

TIP

The API usage is as follows: string|ArrayBuffer FileSystemManager.readFileSync(string filePath, string encoding)
This API is supported by mini programs, but not by mini games.

  • Functional description: FileSystemManager.readFileread local file content. The upper limit of a single file size is 100M

  • Parameters and descriptions:

    • string filePath:path of the file to read
    • string encoding:specify the character encoding of the file to be read. If encoding is not passed, the binary content of the file is read in ArrayBuffer format
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • Return value: string|ArrayBuffer data,Read the local file content

  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.readFile({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  encoding: 'utf8',
  position: 0,
  success(res) {
    console.log(res.data)
  },
  fail(res) {
    console.error(res)
  }
})

// async api
try {
  const res = fs.readFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'utf8', 0)
  console.log(res)
} catch(e) {
  console.error(e)
}

.readZipEntry

TIP

The API usage is as follows: FileSystemManager.readZipEntry(Object object)

  • Functional description: Read the files in the compressed package

  • Parameters and descriptions: Object object

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-Yesthe path of the compressed package to be read (local path)
    encodingstring-Nounified specification of the character encoding of the read file, only valid when the entries value is 'all'. If the entries value is 'all' and encoding is not passed, the binary content of the file is read in ArrayBuffer format
    entriesArray.<Object>/'all'-YesThe list of files in the compressed package to be read (when 'all' is passed, it means reading all files in the compressed package)
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • entries structure attribute

    Structure propertiesTypeDefault valueRequiredDescription
    pathstring-YesFile path in the compressed package
    encodingstring-NoSpecify the character encoding of the file to be read. If encoding is not passed, the binary content of the file is read in ArrayBuffer format. The legal value is the same as encoding
    positionnumber-NoStart reading from the specified position of the file. If not specified, read from the file header. The reading range should be a left-closed and right-open interval position, position+length. Valid range: [0, fileLength - 1]. Unit: byte
    lengthnumber-NoSpecify the length of the file. If not specified, read to the end of the file. Valid range: [1, fileLength]. Unit: byte
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    entriesObjectFile reading result. res.entries is an object, key is the file path, value is an object FileItem, which represents the reading result of the file. Each FileItem contains data (file content) and errMsg (error message) attributes
    • entries structure attribute
    Structure propertiesTypeDescription
    pathstringFile path
    • path structure attribute
    Structure propertiesTypeDescription
    datastring/ArrayBufferfile content
    errMsgstringError message
  • Sample code:

js
const fs = wx.getFileSystemManager()
// Read one or multiple files within a zip.
fs.readZipEntry({
  filePath: 'wxfile://from/to.zip',
  entries: [{
 path: 'some_folder/my_file.txt', // File path within the zip
encoding: 'utf-8', // Specifies the character encoding for reading the file. If 'encoding' is not passed, the file's binary content is read in ArrayBuffer format
position: 0, // Start reading from a specified position in the file; if not specified, reading begins from the start of the file. The reading range should be a left-closed and right-open interval [position, position+length). The valid range is [0, fileLength - 1] in bytes.
    length: 10000, // Specify the length of the file. If not specified, reading continues until the end of the file. The valid range is [1, fileLength] in bytes.
  }, {
    path: 'other_folder/orther_file.txt', // File path within the zip
  }],
      success(res) {
    console.log(res.entries)
    // res.entries === {
    //     'some_folder/my_file.txt': {
    //         errMsg: 'readZipEntry:ok',
    //         data: 'xxxxxx'
    //     },
    //     'other_folder/orther_file.txt': {
    //         data: (ArrayBuffer)
    //  }
    //  }
  },
  fail(res) {
    console.log(res.errMsg)
  },
})

// Reads all files within the zip. A unified 'encoding' can be specified. 'Position' and 'length' can no longer be specified and default to 0 and the file length, respectively.
fs.readZipEntry({
  filePath: 'wxfile://from/to.zip',
  entries: 'all'
encoding: 'utf-8', // Uniformly specifies the character encoding for reading the file. If 'encoding' is not passed, the file's binary content is read in ArrayBuffer format.
      success(res) {
    console.log(res.entries)
    // res.entries === {
    //     'some_folder/my_file.txt': {
    //         errMsg: 'readZipEntry:ok',
    //         data: 'xxxxxx'
    //     },
    //     'other_folder/orther_file.txt': {
    //         errMsg: 'readZipEntry:ok',
    //         data: 'xxxxxx'
    //  }
    //  }
  },
  fail(res) {
    console.log(res.errMsg)
  },
})

.removeSavedFile

TIP

The API usage is as follows: FileSystemManager.removeSavedFile(Object object)

  • Functional description: Delete the local cache files saved under this applet

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to be deleted
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail file not existThe specified tempFilePath cannot find the file

.rename

TIP

The API usage is as follows: FileSystemManager.rename(Object object)

  • Functional description: Rename the file. You can move the file from oldPath to newPath

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    oldPathstring-YesThe source file path can be a normal file or directory, and supports local paths
    newPathstring-YesThe new file path supports local paths
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail permission denied, rename ${oldPath} -> ${newPath}Specify that the source file or target file does not have write permissions
    fail no such file or directory, rename ${oldPath} -> ${newPath}The source file does not exist, or the upper directory of the destination file path does not exist
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.rename({
  oldPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  newPath: `${wx.env.USER_DATA_PATH}/hello_new.txt`,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  const res = fs.renameSync(
    `${wx.env.USER_DATA_PATH}/hello.txt`,
    `${wx.env.USER_DATA_PATH}/hello_new.txt`
  )
  console.log(res)
} catch(e) {
  console.error(e)
}

.renameSync

TIP

The API usage is as follows: FileSystemManager.renameSync(string oldPath, string newPath)
This API is supported by mini programs, but not by mini games.

  • Functional description: FileSystemManager.renameThe synchronous version

  • Parameters and descriptions:

    • string oldPath:The source file path can be a normal file or directory, and supports local paths
    • string newPath:The new file path supports local paths
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.rename({
  oldPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  newPath: `${wx.env.USER_DATA_PATH}/hello_new.txt`,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// async api
try {
  const res = fs.renameSync(
    `${wx.env.USER_DATA_PATH}/hello.txt`,
    `${wx.env.USER_DATA_PATH}/hello_new.txt`
  )
  console.log(res)
} catch(e) {
  console.error(e)
}

.rmdir

TIP

The API usage is as follows: FileSystemManager.rmdir(Object object)

  • Functional description: Delete the directory

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    dirPathstring-YesThe directory path to be deleted
    recursivebooleanfalseNoWhether to recursively delete the directory. If true, delete the directory and all subdirectories and files under the directory
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory ${dirPath}directory does not exist
    fail directory not emptyThe directory is not empty
    fail permission denied, open ${dirPath}The specified dirPath path does not have write permissions
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.rmdir({
  dirPath: `${wx.env.USER_DATA_PATH}/example`,
  recursive: false,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  const res = fs.rmdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
  console.log(res)
} catch(e) {
  console.error(e)
}

.rmdirSync

TIP

The API usage is as follows: FileSystemManager.rmdirSync(string dirPath, boolean recursive)

  • Functional description: FileSystemManager.rmdir The synchronous version

  • Parameters and descriptions:

    • string dirPath: The directory path to be deleted
    • boolean recursive:Whether to recursively delete the directory. If true, delete the directory and all subdirectories and files under the directory
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.rmdir({
  dirPath: `${wx.env.USER_DATA_PATH}/example`,
  recursive: false,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync api
try {
  const res = fs.rmdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
  console.log(res)
} catch(e) {
  console.error(e)
}

.saveFile

TIP

The API usage is as follows: FileSystemManager.saveFile(Object object)

  • Functional description: Save temporary files locally. This interface will move temporary files, so after the call is successful, tempFilePath will not be available

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    tempFilePathstring-YesTemporary storage file path
    filePathstring-NoFile path to be stored
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    savedFilePathnumberThe file path after storage
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail tempFilePath file not existThe specified tempFilePath cannot find the file
    fail permission denied, open "${filePath}"The specified filePath path does not have write permission
    fail no such file or directory "${dirPath}"Parent directory does not exist

.saveFileSync

TIP

The API usage is as follows: number FileSystemManager.saveFileSync(string tempFilePath, string filePath)

  • Functional description: Synchronous version of FileSystemManager.saveFile
  • Parameters and descriptions:
    • string tempFilePath:Temporary storage file path
    • string filePath:File path to be stored
  • Return value: number savedFilePath,The file path after storage

.stat

TIP

The API usage is as follows: FileSystemManager.stat(Object object)

  • Functional description: Get the file Stats object

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    pathstring-YesFile/directory path
    recursivebooleanfalseNoWhether to recursively obtain Stats information for each file in the directory
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    statsStats/ObjectWhen recursive is false, res.stats is a Stats object. When recursive is true and path is a directory path, res.stats is an Object, the key is the relative path of the root path of path, and the value is the Stats object corresponding to the path
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail permission denied, open ${path}The specified path path has no read permission
    fail no such file or directory ${path}The file does not exist
  • Sample code:

    When recursive is false

js
//  synchronous
let fs = wx.getFileSystemManager()
fs.stat({
  path: `${wx.env.USER_DATA_PATH}/testDir`,
  success: res => {
    console.log(res.stats.isDirectory())
  }
})
// sync
fs.statSync(`${wx.env.USER_DATA_PATH}/testDir`, false)
When recursive is true
js
let fs = wx.getFileSystemManager()
// sync
fs.stat({
  path: `${wx.env.USER_DATA_PATH}/testDir`,
  recursive: true,
  success: res => {
    Object.keys(res.stats).forEach(path => {
      let stats = res.stats[path]
      console.log(path, stats.isDirectory())
    })
  }
})
// synchronous
fs.statSync(`${wx.env.USER_DATA_PATH}/testDir`, true)

.statSync

TIP

The API usage is as follows: Stats|Object FileSystemManager.statSync(string path, boolean recursive)

  • Functional description: FileSystemManager.stat The synchronous version

  • Parameters and descriptions:

    • string path:File/directory path
    • boolean recursive:Whether to recursively obtain Stats information for each file in the directory
  • Parameters and descriptions: Stats|Object stats,When recursive is false, res.stats is a Stats object. When recursive is true and path is a directory path, res.stats is an Object, the key is the relative path of the root path of path, and the value is the Stats object corresponding to the path

  • Sample code:

    When recursive is false

js
//  synchronous
let fs = wx.getFileSystemManager()
fs.stat({
  path: `${wx.env.USER_DATA_PATH}/testDir`,
  success: res => {
    console.log(res.stats.isDirectory())
  }
})
// sync
fs.statSync(`${wx.env.USER_DATA_PATH}/testDir`, false)
When recursive is true
js
let fs = wx.getFileSystemManager()
// syn
fs.stat({
  path: `${wx.env.USER_DATA_PATH}/testDir`,
  recursive: true,
  success: res => {
    Object.keys(res.stats).forEach(path => {
      let stats = res.stats[path]
      console.log(path, stats.isDirectory())
    })
  }
})
// synchronous
fs.statSync(`${wx.env.USER_DATA_PATH}/testDir`, true)

.truncate

TIP

The API usage is as follows: FileSystemManager.truncate(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Truncate the file contents.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to be truncated (local path)
    lengthnumber0NoTruncation position, default 0. If length is less than the file length (bytes), only the first length bytes will be retained in the file, and the rest will be deleted; if length is greater than the file length, it will be extended, and the extended part will be filled with null bytes ('\0')
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.truncate({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  length: 10, // from ten bytes to the end
  success(res) {
    console.log(res)
  }
})

.truncateSync

TIP

The API usage is as follows: undefined FileSystemManager.truncateSync(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Truncate the file content (Synchronous version of truncate)

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to be truncated (local path)
    lengthnumber0NoTruncation position, default 0. If length is less than the file length (bytes), only the first length bytes will be retained in the file, and the rest will be deleted; if length is greater than the file length, it will be extended, and the extended part will be filled with null bytes ('\0')
  • Return value: undefined。

  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.truncateSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  length: 10,  // from ten bytes to the end
})

TIP

The API usage is as follows: FileSystemManager.unlink(Object object)

  • Functional description: Delete the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to be deleted
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail permission denied, open ${path}The specified path path has no read permission
    fail no such file or directory ${path}The file does not exist
    fail operation not permitted, unlink ${filePath}The passed filePath is a directory
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.unlink({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

// sync
try {
  const res = fs.unlinkSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
  console.log(res)
} catch(e) {
  console.error(e)
}

.unlinkSync

TIP

The API usage is as follows: FileSystemManager.unlinkSync(string filePath)

  • Functional description: FileSystemManager.unlink The synchronous version

  • Parameters and descriptions: string filePath: The file path to be deleted

  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.unlink({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

try {
  const res = fs.unlinkSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
  console.log(res)
} catch(e) {
  console.error(e)
}

.unzip

TIP

The API usage is as follows: FileSystemManager.unzip(Object object)

  • Functional description: Unzip the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    zipFilePathstring-YesThe source file path can only be a zip compressed file
    targetPathstring-YesThe target directory path
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail permission denied, open ${path}Specified destination file path does not have write permission
    fail no such file or directory ${path}The source file does not exist, or the upper directory of the destination file path does not exist
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.unzip({
  zipFilePath: `${wx.env.USER_DATA_PATH}/example.zip`,
  targetPath: '${wx.env.USER_DATA_PATH}/example',
  success(res) {
    console.log(res)
  },
  fail(res) {
    console.error(res)
  }
})

.write

TIP

The API usage is as follows: FileSystemManager.write(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Write the file

  • Parameters and descriptions: Object object

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    datastring/ArrayBuffer-YesThe text or binary data to be written
    offsetnumber-NoOnly valid when the data type is ArrayBuffer, determines the part to be written in arrayBuffe, that is, the index in arrayBuffer, the default is 6
    lengthnumber-NoOnly valid when the data type is ArrayBuffer, specifies the number of bytes to be written, the default is the number of bytes remaining after arrayBuffer starts at offset bytes from 6
    encodingstringutf8NoSpecify the character encoding for writing to the file.
    positionnumberrNoSpecifies the offset at the beginning of the file, that is, the position where the data is to be written. When position is not passed or a value other than the Number type is passed, the data will be written to the current pointer position
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    bytesWrittennumberThe number of bytes actually written to the file (note that the number of bytes written is not necessarily the same as the number of string characters written)
  • Sample code:

js
const fs = wx.getFileSystemManager()
// open the file
fs.open({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+',
  success(res) {
    // write the file
    fs.write({
      fd: res.fd,
      data: 'some text',
      success(res) {
        console.log(res.bytesWritten)
      }
    })
  }
})

.writeSync

TIP

The API usage is as follows: FileSystemManager.writeFile(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Write the file synchronously

  • Parameters and descriptions: Object object

    PropertiesTypeDefault valueRequiredDescription
    fdstring-YesThe file descriptor that needs to be closed, fd is obtained through FileSystemManager.open FileSystemManager.openSync Interface
    datastring/ArrayBuffer-YesThe text or binary data to be written
    offsetnumber-NoOnly valid when the data type is ArrayBuffer, determines the part to be written in arrayBuffe, that is, the index in arrayBuffer, the default is 6
    lengthnumber-NoOnly valid when the data type is ArrayBuffer, specifies the number of bytes to be written, the default is the number of bytes remaining after arrayBuffer starts at offset bytes from 6
    encodingstringutf8NoSpecify the character encoding for writing to the file.
    positionnumberrNoSpecifies the offset at the beginning of the file, that is, the position where the data is to be written. When position is not passed or a value other than the Number type is passed, the data will be written to the current pointer position
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    bytesWrittennumberThe number of bytes actually written to the file (note that the number of bytes written is not necessarily the same as the number of string characters written)
  • Sample code:

js
const fs = wx.getFileSystemManager()
const fd = fs.openSync({
  filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
  flag: 'a+'
})
const res = fs.writeSync({
  fd: fd,
  data: 'some text'
})
console.log(res.bytesWritten)

.writeFile

TIP

The API usage is as follows: FileSystemManager.writeFile(Object object)

  • Functional description: Write the file

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    filePathstring-YesThe file path to be written
    datastring/ArrayBuffer-YesThe text or binary data to be written
    encodingstringutf-8NoSpecify the character encoding for writing to the file.
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Legal values

    ValueDescription
    ascii-
    base64-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • object.fail callback function parameter: Object res。

    PropertiesTypeDescription
    errMsgstringError message
  • Legal values

    ValueDescription
    fail no such file or directory, open ${filePath}the directory where the specified filePath is located does not exist
    fail permission denied, open ${dirPath}The specified filePath path does not have write permission
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.writeFile({
  filePath: `${wx.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(
    `${wx.env.USER_DATA_PATH}/hello.txt`,
    'some text or arrayBuffer',
    'utf8'
  )
  console.log(res)
} catch(e) {
  console.error(e)
}

.writeFileSync

TIP

The API usage is as follows: FileSystemManager.writeFileSync(string filePath, string|ArrayBuffer data, string encoding)

  • Functional description: FileSystemManager.writeFile The synchronous version

  • Parameters and descriptions:

    • string filePath:The file path to be written
    • string|ArrayBuffer data:The text or binary data to be written
    • string encoding:Specify the character encoding for writing to the file.
  • Legal values

    ValueDescription
    ascii-
    base64 (Note that when selecting base64 encoding, data only needs to pass the base64 content itself, and do not pass the Data URI prefix, otherwise the fail base64 encode error error will be reported. For example, pass aGVsbG8= instead of data:image/png;base64,aGVsbG8= )-
    binary-
    hex-
    ucs2/ucs-2/utf16le/utf-16leRead in little endian
    utf-8/utf8-
    latin1-
  • Sample code:

js
const fs = wx.getFileSystemManager()
fs.writeFile({
  filePath: `${wx.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(
    `${wx.env.USER_DATA_PATH}/hello.txt`,
    'some text or arrayBuffer',
    'utf8'
  )
  console.log(res)
} catch(e) {
  console.error(e)
}

Error code

TIP

Unless otherwise specified, the error codes are subject to the following table

Error codeError messageDescription
1300001operation not permittedThe operation is not allowed (for example, filePath expects to pass a file but actually passes a directory)
1300002no such file or directory ${path}The file/directory does not exist, or the parent directory of the target file path does not exist
1300005Input/output errorThe input and output streams are not available
1300009bad file descriptorInvalid file descriptor
1300013permission deniedPermission error, the file is read-only or write-only
1300014Path permission deniedThe passed path has no permissions
1300020not a directoryThe dirPath specified path is not a directory, which is common when the parent path of the specified write path is a file
1300021Is a directoryThe specified path is a directory
1300022Invalid argumentInvalid parameters, you can check whether length or offset is out of bounds
1300036File name too longThe file name is too long
1300066directory not emptyThe directory is not empty
1300201system errorThe system interface call failed
1300202the maximum size of the file storage limit is exceededInsufficient storage space, or the file size exceeds the upper limit (upper limit 100M)
1300203base64 encode errorCharacter encoding conversion failed (for example, base64 format error)
1300300sdcard not mountedandroid sdcard mount failed
1300301unable to open as fileTypeUnable to open file with fileType
1301000permission denied, cannot access file pathDestination path has no access rights (usr directory)
1301002data to write is emptyWrite data is empty
1301003illegal operation on a directoryThis operation cannot be performed on a directory (for example, the specified filePath is an existing directory)
1301004illegal operation on a package directoryThis operation cannot be performed on a code package directory
1301005file already exists ${dirPath}There is already a file or directory with the same name
1301006value of length is out of rangeThe length passed in is illegal
1301007value of offset is out of rangeThe offset passed in is illegal
1301009value of position is out of rangePosition value is out of bounds
1301100store directory is emptyStore directory is empty
1301102unzip open file failCompressed file opening failed
1301103unzip entry failSingle file decompression failed
1301104unzip failDecompression failed
1301111brotli decompress failBrotli decompression failed (for example, the specified compressionAlgorithm does not match the actual compression format of the file)
1301112tempFilePath file not existThe specified tempFilePath cannot find the file
1302001fail permission deniedThe specified fd path has no read permission/no write permission
1302002exceed max concurrent fd limitThe number of fds has reached the upper limit
1302003invalid flagInvalid flag
1302004permission denied when open using flagCannot use the flag flag to open the file
1302005array buffer does not existArrayBuffer is not passed in
1302100array buffer is readonlyArrayBuffer is read-only

Stats

Object describing the file status

Properties

  • number mode:File type and access permissions, corresponding to POSIX stat.st_mode
  • number size:File size, unit: B, corresponding to POSIX stat.st_size
  • number lastAccessedTime:The time when the file was last accessed or executed, UNIX timestamp, corresponding to POSIX stat.st_atime
  • number lastModifiedTime:The time when the file was last modified, UNIX timestamp, corresponding to POSIX stat.st_mtime

Method set

.isDirectory

TIP

The API usage is as follows: boolean Stats.isDirectory()

  • Functional description: Determine whether the current file is a directory
  • Return value: boolean,Indicates whether the current file is a directory

.isFile

TIP

The API usage is as follows: boolean Stats.isFile()

  • Functional description: Determine whether the current file is a regular file
  • Return value: boolean,Indicates whether the current file is a regular file

ReadResult

  • Functional description: File reading results. Through FileSystemManager.readSync Interface returns
  • Properties
    • number bytesRead,The actual number of bytes read
    • ArrayBuffer arrayBuffer,The object of the buffer area written, that is, the arrayBuffer of the interface input parameter

WriteResult

  • Functional description: File reading results. Through FileSystemManager.writeSync Interface returns
  • Properties number bytesWritten,The number of bytes actually written to the file (note that the number of bytes written is not necessarily the same as the number of string characters written)