sqlite.backup(sourceDb, path[, options])


  • sourceDb DatabaseSync 要备份的数据库。源数据库必须打开。
  • path <string> | <Buffer> | <URL> 将创建备份的路径。如果文件已存在,其内容将被覆盖。
  • options <Object> 备份的可选配置。支持以下属性:
    • source <string> 源数据库的名称。可以是 'main'(默认主数据库)或任何已使用 ATTACH DATABASE 添加的其他数据库。默认值: 'main'
    • target <string> 目标数据库的名称。可以是 'main'(默认的主数据库),也可以是通过 ATTACH DATABASE 添加的其他数据库。默认值: 'main'
    • rate <number> 每批备份要传输的页面数量。默认值: 100
    • progress <Function> 一个可选的回调函数,在每个备份步骤完成后调用。传递给此回调的参数是一个 <Object>,包含 remainingPagestotalPages 属性,用于描述备份操作的当前进度。
  • 返回值:<Promise> 一个在完成时返回备份页面总数的 Promise,如果发生错误则拒绝。

此方法用于进行数据库备份。此方法对 sqlite3_backup_init()sqlite3_backup_step()sqlite3_backup_finish() 功能进行了抽象。

【This method makes a database backup. This method abstracts the sqlite3_backup_init(), sqlite3_backup_step() and sqlite3_backup_finish() functions.】

在备份过程中,已备份的数据库可以正常使用。来自同一连接——相同的 DatabaseSync——对象的修改会立即反映在备份中。但是,来自其他连接的修改会导致备份过程重启。

【The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same DatabaseSync - object will be reflected in the backup right away. However, mutations from other connections will cause the backup process to restart.】

const { backup, DatabaseSync } = require('node:sqlite');

(async () => {
  const sourceDb = new DatabaseSync('source.db');
  const totalPagesTransferred = await backup(sourceDb, 'backup.db', {
    rate: 1, // Copy one page at a time.
    progress: ({ totalPages, remainingPages }) => {
      console.log('Backup in progress', { totalPages, remainingPages });
    },
  });

  console.log('Backup completed', totalPagesTransferred);
})();import { backup, DatabaseSync } from 'node:sqlite';

const sourceDb = new DatabaseSync('source.db');
const totalPagesTransferred = await backup(sourceDb, 'backup.db', {
  rate: 1, // Copy one page at a time.
  progress: ({ totalPages, remainingPages }) => {
    console.log('Backup in progress', { totalPages, remainingPages });
  },
});

console.log('Backup completed', totalPagesTransferred);