Nodejs makes a document synchronization tool to automatically synchronize to gitee implementation code

Nodejs makes a document synchronization tool to automatically synchronize to gitee implementation code

Original Intention

The reason for making this tool is to allow myself to record my daily work or life at any time when using the computer. Usually just record it briefly. This way I can see the records at home and at work simultaneously.

In this way, when you organize it later, you will be able to remember specific things when you see a few keywords. Some of them can also be used as a draft for organizing them into an article in the future. In this way, the article can have a beginning and an end. Otherwise, it will be very detrimental to writing an article if you just say whatever you think of.

At first I used manual synchronization, but found it troublesome, so I just used a batch file to synchronize all at once.

git pull

git add .

git commit -m 'sync'

git push

git status

@echo off

pause

But there are still several disadvantages:

1. Sometimes I forget to perform synchronization, especially when I get off work and turn off the computer directly.

2. If you forget to synchronize at the beginning, git conflicts will occur later. The experience was not very good.

Writing Programs

Nodejs and git need to be installed on your computer by default.

Because later I took the time to write a small program. As long as you run the program in the background, the documents will be automatically synchronized every once in a while.

The modified local content will be automatically synchronized to the git repository. After the git repository content is changed, the latest content will be automatically pulled and synchronized to the local. This ensures that the remote repository and the local are up to date, and the content of the two computers is directly synchronized.

Let's see how to implement it using nodejs:

First we must have a git repository to store data.

Just go to gitee.com and apply to open a warehouse. After creation, get the address of the remote warehouse and copy it for later use.

Create a local folder for synchronizing document data.

Execute npm init -y in the file to create package.json

To bind a remote repository:

git init #Initialize the warehousegit remote add origin [your warehouse address] 
git push origin 
git push --set-upstream origin master #First synchronization of warehouse

After this you can run the tool directly.

Add a new file index.js to the folder

Install dependent packages in the folder

yarn add child_process
yarn add iconv-lite
yarn add moment

Write the code in index.js:

const child_process = require("child_process");
const iconv = require("iconv-lite");
const moment = require("moment");

const encoding = "cp936";
const binaryEncoding = "binary";

//Execute a line of cmd command function cmd(text) {
  return new Promise((resolve, reject) => {
    child_process.exec(
      text,
      { encoding: binaryEncoding },
      (err = "", stdout = "", stderr) => {
        if (err) {
          resolve(err);
          return;
        }
        resolve(iconv.decode(Buffer.from(stdout, binaryEncoding), encoding));
      }
    );
  });
}

//cmd running order async function run() {
  const time = moment().format("YYYY-MM-DD HH:mm:ss");
  let status = await cmd("git status");
  if (
    status.includes(
      "not a git repository (or any of the parent directories): .git"
    )
  ) {
    //The directory is not bound to the git address console.log("The directory is not bound to the git address");
  } else {
    //Bound to git
    //Pull const pull = await cmd("git pull");
    if (
      !pull.includes("Already up to date") &&
      !pull.includes("Already up-to-date")
    ) {
      // Pull down the latest data console.log(`Pull down the latest data: ${time}`);
    }
    //status status = await cmd("git status");
    if (status.includes('(use "git add"')) {
      //Local content has been changed and needs to be submitted await cmd("git add .");
      await cmd('git commit -m "sync"');
      await cmd("git push");
      console.log(`Synchronization successful: ${time}`);
    }
  }
}

//Execute every 30 seconds setInterval(() => {
  run();
}, 1000 * 30);
run();

This doesn't work because we want to synchronize files in the specified directory, not the current directory. So we have to package it into an exe file and put it in the folder that needs to be synchronized in order to synchronize the specified directory.

First, we install a dependency package globally: pkg

npm install -g pkg

Then execute in the tool directory:

pkg -t win index.js

You can package the nodejs project into an independent exe program, and then put the exe program in the directory that needs git synchronization.

In addition, in order not to synchronize this exe file to the warehouse, we need to exclude this file

So put a .gitignore file in the synchronized directory and add a line to remove the exe file

This packaged file: http://xiazai.jb51.net/202112/yuanma/indexdat_jb51.rar

This configuration file: http://xiazai.jb51.net/202112/yuanma/gitignore_jb51.rar

In order to enable the program to be started directly after the computer is turned on, we put the program into the startup item

Open the folder, then paste this path into the folder and press Enter

%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

We put the shortcut of this file into the startup item, so that synchronization will be performed when the computer is turned on, achieving constant synchronization. Every 30 seconds it will check if it is up to date.

This is the end of this article about how to make a document synchronization tool in nodejs to automatically synchronize to gitee. For more related nodejs document synchronization tool content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the idea of ​​implementing a word document parser in nodejs
  • Nodejs (officegen) + vue (axios) method to export word documents on the client
  • nodejs npm package.json Chinese documentation

<<:  Pure CSS to achieve the list pull-down effect in the page

>>:  How to write object and param to play flash in firefox

Recommend

Interviewers often ask questions about React's life cycle

React Lifecycle Two pictures to help you understa...

select the best presets to create full compatibility with all browsersselect

We know that the properties of the select tag in e...

How to smoothly go online after MySQL table partitioning

Table of contents Purpose of the table For exampl...

MySQL common statements for viewing transactions and locks

Some common statements for viewing transactions a...

Markup language - specify CSS styles for text

Click here to return to the 123WORDPRESS.COM HTML ...

JavaScript to achieve fireworks effects (object-oriented)

This article shares the specific code for JavaScr...

How to use Nginx to solve front-end cross-domain problems

Preface When developing static pages, such as Vue...

A brief discussion on several situations where MySQL returns Boolean types

mysql returns Boolean type In the first case, ret...

Understanding MySQL precompilation in one article

1. Benefits of precompilation We have all used th...

Vue uses echart to customize labels and colors

This article example shares the specific code of ...

What is the base tag and what does it do?

The <base> tag specifies the default addres...

Detailed explanation of Linux command unzip

Table of contents 1. unzip command 1.1 Syntax 1.2...