Share a section to upload the compiled front-end Dist folder to Ali OSS

IT200 navigates for you

1. Install Ali-OSS and import related dependencies

/** * npm install ali-oss --save */
const path = require("path");
const fs = require("fs");
const OSS = require("ali-oss");
Copy the code

2. Create an OSS client

const client = new OSS({
  bucket: "".region: "".accessKeyId: "".accessKeySecret: ""
});
Copy the code

3. Traverse the path to obtain all files in the dist folder

const rootPath = path.resolve(__dirname, "./dist");
let filepaths = [];
let putCount = 0;

function readFileSync(filepath) {
  let files = fs.readdirSync(filepath);
  files.forEach(filename= > {
    let p = path.join(filepath, filename);
    let stats = fs.statSync(p);
    if (stats.isFile()) {
      filepaths.push(p);
    } else if(stats.isDirectory()) { readFileSync(p); }}); }Copy the code

4. Add the file path to the OSS client

function put(filepath) {
  const p = filepath.replace(rootPath, "").substr(1);
  return client.put(p.replace("\ \"."/"), filepath);
}
Copy the code

5. Perform the task of uploading the consuming OSS client

async function update() {
  try {
    // Get all files to be uploaded recursively
    readFileSync(rootPath);
    let retAll = await filepaths.map(filepath= > {
      putCount++;
      console.log('Task add:${path.basename(filepath)}`);
      return put(filepath);
    });
    Promise.all(retAll).then(res= > {
      const resAll = res.map(r= > {
        return r.res.statusCode === 200;
      });
      if (Object.keys(resAll).length === putCount) {
        console.log("Successful release"); }}); }catch (e) {
    console.log(e); }}Copy the code

6. Run

// Perform upload
update();
Copy the code