Table of Contents
Principle
Execution process
Development process
Script function
Use
Home Web Front-end JS Tutorial Take you step by step to develop a mobile phone backup gadget using Node.js and adb

Take you step by step to develop a mobile phone backup gadget using Node.js and adb

Apr 14, 2022 pm 09:06 PM
node.js

This article will share with you a Node practical experience and introduce how to develop a mobile phone backup gadget using Node.js and adb. I hope it will be helpful to everyone!

Take you step by step to develop a mobile phone backup gadget using Node.js and adb

With the development of technology, the definition of the pictures and videos we take in our daily life continues to improve, but this also has a major disadvantage, that is, their size is also getting larger and larger. big. I still remember that when I first started using smartphones, a photo was only 2-5MB, but now a photo has reached 15-20MB, or even larger.

Take you step by step to develop a mobile phone backup gadget using Node.js and adb

#The storage space on our mobile phones is limited. How do we back up these photos and videos to free up space on our mobile phones?

So, at the beginning, I stored all these data in a photo album cloud. Although the problem of storing these data was solved, new problems also emerged, such as upload size constraints and the need to Occupying the background leads to increased power consumption and advertising.

I simply stopped using it later and wrote a script myself to back up the data, so I came up with this article.

I used Node.js and adb to make this script and named it MIB

Principle

This gadget is debugged using adb on the mobile phone and reads the file information in the mobile phone through the shell command And copy, move the files in the mobile phone.

Execution process

I drew a simple flow chart, MIB will first read the configuration file (if not, create the configuration file), Read the node path that needs to be backed up according to the configuration file and perform file backup operations. until the end of the node.

Take you step by step to develop a mobile phone backup gadget using Node.js and adb

Development process

Installing the required environment

  • Downloadadb package, used to perform various device operations

  • DownloadNode.js, I believe this Brothers already have

  • installed dependency libraries on their computers

    • fs-extra: based on fsModule secondary encapsulation Node library
    • prompts: Node library for interaction on the command line
    • winston: Node library for recording script logs

Since the project source code is a bit too much, I only put the main ones here Code part

Interested friends can go to github to see the project source codegithub.com/QC2168/mib

Read configuration file

export const getConfig = (): ConfigType => {
  if (existConf()) {
    return readJsonSync(CONFIG_PATH);
  }
  // 找不到配置文件
  return createDefaultConfig();
};
Copy after login

When executing the script, select the device ID that needs to be backed up. And specify the device when executing the adb command

(async () => {
  const device: string | boolean = await selectDevice();
  if (device) MIB();
})();

export const selectDevice = async ():Promise<string|false> => {
  // 获取设备
  const list: devicesType[] = devices();

  if (list.length === 0) {
    log("当前无设备连接,请连接后再执行该工具", "warn");
    return false;
  }

  const result = list.map((i) => ({ title: i.name, value: i.name }));

  const { value } = await prompts({
    type: "select",
    name: "value",
    message: "please select your device",
    choices: result,
  });
  currentDeviceName = value;
  return currentDeviceName;
};
Copy after login

Traverse the backup node

After selecting the device, enter the traversal node information , and execute the copy file to the specified path (output attribute in the configuration file)

const MIB = () => {
  // 获取配置文件
  const { backups, output } = getConfig();
  // 判断备份节点是否为空
  if (backups.length === 0) {
    log("当前备份节点为空", "warn");
    log("请在配置文件中添加备份节点", "warn");
  }
  if (backups.length > 0) {
    isPath(output);
    // 解析备份路径最后一个文件夹
    backups.forEach((item: SaveItemType) => {
      log(`当前执行备份任务:${item.comment}`);
      const arr = item.path.split("/").filter((i: string) => i !== "");
      const folderName = arr.at(-1);
      const backupDir = pathRepair(item.path);
      // 备份目录
      // 判断节点内是否有备份目录  // 拼接导出路径
      const rootPath = pathRepair(pathRepair(output) + folderName);
      const outputDir = item.output
        ? item.output && pathRepair(item.output)
        : rootPath;
      // 判断备份路径是否存在
      if (!isPathAdb(backupDir)) {
        log(`备份路径:${backupDir} 不存在已跳过`, "error");
      } else {
        // 判断导出路径
        isPath(outputDir);
        backup(backupDir, outputDir, item.full);
      }
    });
  }
  log("程序结束");
};


// 细化需要备份的文件,进入备份队列中
const backup = (target: string, output: string, full: boolean = false) => {
  if (!full) {
    // 备份非备份的文件数据
    // 获取手机中的文件信息,对比本地
    const { backupQueue } = initData(target, output);
    // 计算体积和数量
    computeBackupSize(backupQueue);
    // 执行备份程序
    move(backupQueue, output);
  } else {
    // 不文件对比,直接备份
    moveFolder(target, output);
  }
};


// 移动待备份文件队列中的文件
const move = (backupQueue: FileNodeType[], outputDir: string): void => {
  if (backupQueue.length === 0) {
    log("无需备份");
    return;
  }
  for (const fileN of backupQueue) {
    log(`正在备份${fileN.fileName}`);
    try {
      const out: string = execAdb(
        `pull "${fileN.filePath}" "${outputDir + fileN.fileName}"`,
      );
      const speed: string | null = out.match(speedReg) !== null ? out.match(speedReg)![0] : "读取速度失败";
      log(`平均传输速度${speed}`);
    } catch (e: any) {
      log(`备份${fileN.fileName}失败 error:${e.message}`, "error");
    }
  }
};
Copy after login

Script function

  • USBConnection backup data
  • Wireless connection backup data
  • Multiple device backup selection
  • Single node full backup

Use

Enter the following command in the terminal to install globally mib.

npm i @qc2168/mib -g
Copy after login

Configuration script file

For first time use, you need to create a new .mibrc file in the user directory and set the corresponding parameter content.

{
    "backups": [
        {
            "path": "/sdcard/MIUI/sound_recorder/call_rec",
            "comment": "通话录音"
        },
        {
            "path": "/sdcard/DCIM/Camera",
            "comment": "本地相册"
        },
        {
            "path": "/sdcard/DCIM/Creative",
            "comment": "我的创作"
        },
        {
            "path": "/sdcard/Pictures/weixin",
            "comment": "微信相册"
        },
        {
            "path": "/sdcard/tencent/qq_images",
            "comment": "QQ相册"
        },
        {
            "path": "/sdcard/Pictures/知乎",
            "comment": "知乎"
        },
        {
            "path": "/sdcard/tieba",
            "comment": "贴吧"
        },
        {
            "path": "/sdcard/DCIM/Screenshots",
            "comment": "屏幕截屏"
        },
        {
            "path": "/sdcard/DCIM/screenrecorder",
            "comment": "屏幕录制"
        },
        {
            "path": "/sdcard/MIUI/sound_recorder",
            "comment": "录音"
        },
        {
            "path": "/sdcard/MIUI/sound_recorder/app_rec",
            "comment": "应用录音"
        }
    ],
    "output": "E:/backups/MI10PRO"
}
Copy after login

Perform backup

In the console, directly enter mib to trigger the script without other parameters.

mib
Copy after login

The console will output corresponding information based on the configuration file.

2022-04-09 20:58:11 info 当前执行备份任务:屏幕录制
2022-04-09 20:58:11 info 备份数量1
2022-04-09 20:58:11 info 已获取数据24Mb
2022-04-09 20:58:11 info 备份体积24Mb
2022-04-09 20:58:11 info 正在备份Screenrecorder-2022-04-08-19-45-51-836.mp4
2022-04-09 20:58:12 info 平均传输速度27.7 MB/s
2022-04-09 20:58:12 info 当前执行备份任务:录音
2022-04-09 20:58:12 info 备份数量0
2022-04-09 20:58:12 info 备份体积0Mb
2022-04-09 20:58:12 info 无需备份
2022-04-09 20:58:13 info 程序结束
Copy after login

Original address: https://juejin.cn/post/7084889987631710221

Author: _island

For more node-related knowledge, please visit : nodejs tutorial!

The above is the detailed content of Take you step by step to develop a mobile phone backup gadget using Node.js and adb. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

If ADB is not recognized in Windows 11, do the following If ADB is not recognized in Windows 11, do the following May 19, 2023 pm 04:08 PM

If you're trying to flash a custom ROM, recover your phone from a boot loop, or unlock the bootloader, ADB and Fastboot will be your best friends. ADB helps you install apps on your phone, uninstall system apps without rooting your device, get app logs, issue commands to apps, and generally communicate with your Android device. Fastboot and ADB are two of the most important tools when using Android devices. However, many people often encounter problems when trying to use ADB and Fastboot for the first time. The ADB not recognized error is common for people trying to set up ADB for the first time, but for people who have

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

How to download and install the ADB driver on Windows 11 How to download and install the ADB driver on Windows 11 Apr 13, 2023 pm 11:19 PM

ADB is a command line tool that allows users to perform complex and unrestricted changes on Android devices. You can use it to perform app sideloading, custom ROM flashing and firmware upgrades, and other advanced tweaks. The ADB driver facilitates this process and ensures that ADB works as expected. However, like earlier operating systems, ADB does not come preinstalled on Windows 11. Therefore, you must install the driver yourself. In this tutorial, we not only show you how to install the ADB driver, but we also take you through the configuration process. Are ADB drivers safe to install? ADB drivers are generally safe. They won't do anything unnecessary to your PC

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

See all articles