1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| const path = require('path'); const Client = require('ssh2-sftp-client'); const fs = require('fs');
const sftp = new Client(); const config = { host: '', port: '22', username: 'root', password: '' } const waitFileList = [] let fileCount = 0
function startUpload() { const p = path.resolve(__dirname, './source/_posts') fs.readdir(p, (err, files) => { if (err) throw err; fileCount = files.length files.forEach(file => { updateFile(file) }); });
}
function updateFile(fileName) { const filePath = path.resolve(__dirname, './source/_posts/' + fileName) fs.readFile(filePath, 'utf8', (err, data) => { fileCount-- if (err) throw err;
if (/\(..\/images\/[\w-]+.[A-Za-z]+\)/g.test(data)) { console.log(fileName) const regex = /\(..\/images\/[\w-]+.[A-Za-z]+\)/g; const fileNames = data.match(regex); const names = fileNames.map(item => { return item.substring(11, item.length - 1) }) waitFileList.push(...names) const modifiedData = data.replace(/..\/images\//g, 'https://yifengtingyu.cn/img/hexo/') fs.writeFile(filePath, modifiedData, 'utf8', (err) => { if (err) throw err; console.log('修改文件' + fileName); }); } if (fileCount <= 0 && waitFileList.length) { upload(waitFileList) } }); }
function upload(fileNames) { sftp.connect(config).then(() => { console.log('sftp链接成功'); let r fileNames.forEach(fileName => { console.log('文件上传中:' + fileName); r = sftp.put(path.resolve(__dirname, './source/images/' + fileName), '/home/zou/www/img/hexo/' + fileName); }) return r }).then((data) => { console.log('文件上传成功'); sftp.end(); }).catch((err) => { console.log('上传失败', err); sftp.end(); }) }
startUpload()
|