基於阿里的Node全棧之路(四)前後端分離進階-自動上傳前端程式碼到OSS

木木工程師發表於2017-09-26

上一篇文章提到我們是人工上傳構建後的程式碼的,作為一個自認自動化運維程度算比較高的我,怎麼能忍受嘞,怎麼也得是自動的吧!

我其實也嘗試過github上有人分享過類似的外掛,但發現都不能用,而且都很久沒維護來,所以,只能自己來搞了。

這裡,貼下我的自動上傳程式碼,在www檔案建立一個index.js

const fs = require(`fs`);
const co = require(`co`);
const path = require(`path`);
const oss = require(`ali-oss`);

//構建oss物件
const store = oss({
  accessKeyId: `accessKeyId`,
  accessKeySecret: `accessKeySecret`,
  bucket: `bucket`,
  region: `oss-cn-shenzhen`,
});

(() => {
  const root = path.resolve(__dirname, `./dist`);
  const files = [];
  //遞迴取出所有資料夾下所有檔案的路徑
  function readDirSync(p) {
    const pa = fs.readdirSync(p);
    pa.forEach((e) => {
      const cur_path = `${p}/${e}`;
      const info = fs.statSync(cur_path);
      if (info.isDirectory()) {
        readDirSync(cur_path);
      } else {
        files.push(cur_path);
      }
    });
  }
  readDirSync(root);

  co(function* () {
    //遍歷檔案
    for (let index = 0; index < files.length; index += 1) {
      const e = files[index];
      const result = yield store.put(e.replace(root, ``), e);
      //提交檔案到oss,這裡要注意,阿里雲不需要建立新資料夾,只有有路徑,沒有資料夾會自動建立
      console.log(result);
    }
  });
})();

然後再執行

node index.js


相關文章