search
HomeWeb Front-endJS TutorialTake you step by step to develop a mobile phone backup gadget using Node.js and adb

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

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

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

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

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"
}

Perform backup

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

mib

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 程序结束

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software