Node copy folder, compress zip, upload

Source: Internet
Author: User
Tags create directory unique id

A: The module used and a brief introduction of NPM documentation;
Request:node the requested module, which can be used to request the server's interface
Https://www.npmjs.com/package/request
FS: Read and write files, very common
Https://www.npmjs.com/package/fs
Path: Paths, various paths to folders, whatever.
Https://www.npmjs.com/package/path
Js-cookie: Get Cokie, need to use when request
Https://www.npmjs.com/package/js-cookie
Node-native-zip: compressing the zip module

Public Introduction module, const PATH = require ("path"), const FS = require ("FS"), var request = require ("request"), var zip = require ("Node-na Tive-zip ");

  

II: Copy folder;
Project background:
has an absolute path to the project;
e:/183svn/ appstore183
where appstore183 is the directory of the app, which is a variety of code, you need to compress the code zip and then upload to the designated server;
but the compressed zip format has to be Appid.zip, here AppID is the project's unique ID, is a bunch of numbers, assuming
appid=123456789;
Compressed zip is 123456789.zip, the structure is
123456789/ APPSTOR183/below is the code
so the original path e:/183svn/appstore183 not meet the requirements, so choose to copy the path I need

First step replication: Due to the need of the ZIP structure package I need the last path for the copy to e:/183svn/appstore183/123456789/123456789/appstore183/below is a variety of code files; The code is implemented as follows: Var AppID =opt.appid;//123456789var localpath=apicloudstudio.localprojects[0].localpath;//project Directory E:\183svn\appstore183// Note Appid,localpath are all other programs get the value or cookie given, here first think of writing dead; var pathrr=localpath.split (' \ \ '); var appdirpath =pathrr[ pathrr.length-1];//Project name//appstore183var appparentdirpath =localpath.replace (' \ \ ' +appdirpath, ');//project Parent name//E:\ 183svn//Note: Here with the JS split string method to obtain the path, it is troublesome, you can directly use the Path module method//Copy the project directory to the temporary directory let ContainerDir0 = Path.join (Appparentdirpath, AppID);//e:\183svn\123456789let containerdir = Path.join (containerdir0,appid);//e:\183svn\123456789 This is the target directory to copy if ( Fs.existssync (CONTAINERDIR0)) {//has already created this directory removed if (Fs.statsync (CONTAINERDIR0). Isdirectory ()) {deletefolderrecursive (c  ONTAINERDIR0);  } else {Fs.unlinksync (CONTAINERDIR0); }}if (Fs.existssync (Containerdir)) {//has already created this directory with the delete if (Fs.statsync (Containerdir). Isdirectory ()) {Deletefolderrecursiv  E (Containerdir); } else {Fs.unlinksYnc (Containerdir);  }}fs.mkdirsync (CONTAINERDIR0);//Create Directory Fs.mkdirsync (containerdir);//create directory let copy = function (src, DST) {//Read all files/directories in directory  Let paths = Fs.readdirsync (src);    Paths.foreach (function (item) {Let _src = Path.join (src, item);    Let _DST = Path.join (DST, item);    Let readable,writable;    if (Fs.statsync (_SRC). Isdirectory ()) {//is directory exists (_SRC, _DST, copy);      } else {//is file readable = Fs.createreadstream (_SRC);      writable = Fs.createwritestream (_DST);    Readable.pipe (writable); }  });};  Let exists = function (src, DST, callback) {if (Fs.existssync (DST)) {callback (SRC, DST);    } else {fs.mkdirsync (DST);  Callback (SRC, DST);  }};let copytree = function (src, DST) {Let objsrc = Path.parse (src);  Let dirName = Objsrc.name;  Let TargetDir = Path.join (DST, dirName);    if (Fs.existssync (TargetDir)) {if (Fs.statsync (TargetDir). Isdirectory ()) {deletefolderrecursive (TargetDir); } else {Fs.unlinksync (targetDir);    }} fs.mkdirsync (TargetDir); Copy (SRC, targetDir);};  Copytree (LocalPath, containerdir); function deletefolderrecursive (path) {Let files = [];    if (Fs.existssync (path)) {files = Fs.readdirsync (path);      Files.foreach (function (file,index) {Let Curpath = path + "/" + file;      if (Fs.statsync (Curpath). Isdirectory ()) {//Recurse deletefolderrecursive (Curpath);      } else {//delete file Fs.unlinksync (Curpath);    }    });  Fs.rmdirsync (path); }}//Copy the project directory to the TEMP directory end here The copy is done, and this also copies the hidden folder and the following file

  

Step two: Compress zipCompress temp directory var outputpath=path.join (Path.dirname (containerdir), appid+ '. zip ');//output Zip path//e:183svn/123456789.zip Here is the configuration to compress the zip file into the directory and the name//to compress the folder where the parent directory let Pathtozipdir = Path.dirname (Containerdir); ' e:183svn/123456789/';//Note: The path to the code file now is ' e:183svn/123456789/123456789/appstore183/inside a bunch of files In order to compress the zip inside a layer of 123456789 folders so that the parents of compressed files jump two layer//To compress the folder in the last layer directory let Dirtozip = AppID; 123456789/appstore183 ';//is the path of a bunch of files, also for the format of the ZIP package there is a Layer 123456789 folder (function () {Let zip = require ("Node-native-zip"  );  Let archive = new zip ();       (function AddFile (filepath) {if (Fs.lstatsync (filepath). Isdirectory ()) {Let directory = Fs.readdirsync (filepath);      Directory.foreach (function (Subfilepath) {AddFile (Path.join (Filepath,subfilepath));    });    } else {Archive.add (path.relative (Pathtozipdir, filepath), Fs.readfilesync (filepath, ' binary '));  }}) (Path.join (Pathtozipdir, dirtozip));  Let buff = Archive.tobuffer ();    Fs.writefile (OutputPath, Buff, function () {Console.log ("compression finished"); ConsOle.log (' Compressed package path: ' +outputpath);    //Part III//upload zipUpload with request module, format and the Ajax feeling of JQ almost let me particularly like, haha directly request an interface, Formdtata inside the file files with FS read into the form of stream, Duang suddenly upload request ({URL: ' ${WINDOW.L Ocation.origin}/api2/upload ', Method: "POST", FormData: {upload_type: "Zip", file:fs.createReadSt Ream (OutputPath)}, headers:{"cookie": opt.cookie//other send Get cookie}},function (err, response, b      Ody) {//callback inside handles success and failure if (err) {Console.log (err);      }else{Callback (Json.parse (body). Result.path); }    })  });} ());//Compress temp directory End

In general, are copied Baidu to the code and reference project inside the code of the predecessor implementation, the function is realized, but certainly not the best approach, but also hope that there are better solutions to the big boys fly

Node copy folder, compress zip, upload

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.