I came across an article called Ditch Jenkins, Embrace Node. It didn’t interest me to read it, but it inspired me to write an automatic deployment script

The node directive used in this article is generated in the previous article, interested can jump to the past: juejin.cn/post/684490…

Using the Technology stack

  • Ssh2 (Logging in to the server using SSH)
  • Fs (File Processing)
  • Compress (Compressed script)

Mind maps

Code compression

 compressing.zip
 .compressDir('./dist/.'.'./dist.zip').then(() => {console.log(' Tip: file compression succeeded '); conFun() }) .catch(err => { console.log("Tip: Compression error");
     console.error(err);
 });

Copy the code

Using the function: compressing.zip.com pressDir (source, dest, opts)

Note!!!!!! Dist /dist/. = ‘./dist/.’ = ‘./dist/.’

The connection function

const params = {file: `./dist.zip`, target: `${servicePath}/dist. Zip '} // join functionfunction conFun(){
  console.log('Start connecting... ');
  
  connection = new ssh2();
  connection.connect({
      "host": ip ,
      "username": user,
      "password": password
  });
  connection.on('error'.function (err) {
      connection.end()
      console.log('Connection failed');
  });
  connection.on('ready'.function() { upLoadFile(connection, params) }); } // Upload functionfunction upLoadFile(conn, params) {
    const file = params.file  
    const target = params.target
    if(! conn) {return
    }
    conn.sftp(function (err, sftp) {
        if (err) {
            throw err
        }
        sftp.fastPut(file, target, {}, function (err, result) {
            if(err) {throw err} // Execute Linux command Shell(conn)})})}Copy the code

Params {file: localPath, target: servicePath}, file stores the compressed local dist file. Target is the address where the server is deployed

Executing script functions

// Execute the script function const comment = [cd ${servicePath}`,
  'unzip -o dist.zip'.'rm -f dist.zip'.'exit'.'close'
]

function Shell(conn) {
    conn.shell(function (err, stream) {
        if (err) throw err;
        stream.on('close'.function () {
          console.log('Release complete!! '); // Delete fs.unlinksync ('./dist.zip')
          conn.end();
        }).on('data'.function (data) {
          console.log('STDOUT: ' + data)
        });
        stream.end(comment.join('\n'));
    });
    
}
Copy the code

Decompress the Dist zip on the server, and then delete the zip.

Execute the upload script after packaging

After installing the Node directive, simply add the pack directive to vue’s pack directive

This way we only need to automatically upload the code to the specified server after the NPM run build is packaged to complete automatic deployment.

perfect

If multiple projects require multiple deployment environments, you can define environment variables to determine the deployment environment.

Code: github.com/justworkhar…