On this page

    M

    sqlite.backup

    History
    sqlite.backup(sourceDb, path, options?): Promise
    Attributes
    sourceDb:DatabaseSync
    The database to backup. The source database must be open.
    path:string | Buffer | URL
    The path where the backup will be created. If the file already exists, the contents will be overwritten.
    options:Object
    Optional configuration for the backup. The following properties are supported:
    source?:string
    Name of the source database. This can be 'main' (the default primary database) or any other database that have been added with ATTACH DATABASE Default: 'main'.
    target?:string
    Name of the target database. This can be 'main' (the default primary database) or any other database that have been added with ATTACH DATABASE Default: 'main'.
    rate?:integer
    Positive number of pages to be transmitted in each batch of the backup. Default: 100.
    progress:Function
    An optional callback function that will be called after each backup step. The argument passed to this callback is an Object with remainingPages and totalPages properties, describing the current progress of the backup operation.
    Returns:Promise
    A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an error occurs.

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

    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);