const fs = require('fs'); const path = require('path'); const https = require('https'); const { URL } = require('url'); var filePath = path.resolve('assets/'); const options = { method: 'POST', hostname: 'tinypng.com', path: '/web/shrink', headers: { rejectUnauthorized: false, 'Postman-Token': Date.now(), 'Cache-Control': 'no-cache', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', }, }; fileDisplay(filePath); function getRandomIP() { return Array.from(Array(4)) .map(() => parseInt(Math.random() * 255)) .join('.'); } function fileDisplay(filePath) { fs.readdir(filePath, function (err, files) { if (err) { console.warn(err); } else { files.forEach(function (filename) { var filedir = path.join(filePath, filename); fs.stat(filedir, function (eror, stats) { if (eror) { } else { var isFile = stats.isFile(); var isDir = stats.isDirectory(); if (isFile) { if ( filedir.includes('.png') && !filedir.includes('.meta') ) { options.headers['X-Forwarded-For'] = getRandomIP(); fileUpload(filedir); } } if (isDir) { fileDisplay(filedir); } } }); }); } }); } function fileUpload(img) { var req = https.request(options, function (res) { res.on('data', (buf) => { let obj = JSON.parse(buf.toString()); if (obj.error) { } else { fileUpdate(img, obj); } }); }); req.write(fs.readFileSync(img), 'binary'); req.on('error', (e) => { console.error(e); }); req.end(); } function fileUpdate(imgpath, obj) { console.log('update img' + imgpath); let options = new URL(obj.output.url); let req = https.request(options, (res) => { let body = ''; res.setEncoding('binary'); res.on('data', function (data) { body += data; }); res.on('end', function () { fs.writeFile(imgpath, body, 'binary', (err) => { if (err) return console.error(err); }); }); }); req.on('error', (e) => { console.error(e); }); req.end(); }