我们经常在使用别人图片url的时候发现图片显示不了,很可能对方做防盗链处理。在浏览器端有这个限制但是在后端就没有这个问题了。所以我们可以通过图片的url在服务端将这个图片下载下来保存在服务器上,然后客户端去访问我们自己的服务器,为了保证最小的改动,最好是保持原来url的图片路径,我们只需要换url前面的域名就可以了。

分析源url,创建本地目录以及解析出新的写入路径

使用mkdirSync函数同步的进行循环递归创建目录

function mkdirSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirSync(path.dirname(dirname))) {   
            fs.mkdirSync(dirname);
            return true;
        }
    }
    return false
}

如:http://api.3inns.cn/mito/uploadImages/2015/355/17/8032VO7EM87O_113.jpg,的图片路径应该是: 当前目录/mito/uploadImages/2015/355/17/8032VO7EM87O_113.jpg

下载并写入

request(url).pipe(fs.createWriteStream(dstpath))

完整代码如下:

var request = require('request')
var fs = require('fs')
var path = require('path')

const dirname = 'uploadImages'
const hostdir = "./public/mito/"
function mkdirSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirSync(path.dirname(dirname))) {   
            fs.mkdirSync(dirname);
            return true;
        }
    }
    return false
}

function downloadUrl(urlList) {
    for (const url of urlList) {
      const first = url.indexOf(dirname)
      const last = url.lastIndexOf('/')
      if (first > 0 && last > 0) {
        const name = url.substr(last + 1)
        const dir = url.substr(first, last - first)
        const dstpath = hostdir + dir + '/' + name
        if (name.length && dir.length && !fs.existsSync(dstpath)) {
          if (mkdirSync(hostdir + dir)) {
            console.log(dstpath)
            request(url).pipe(fs.createWriteStream(dstpath))
          }
        }
      }
    }
}

删除大于100k的文件

var exec = require('child_process').exec;
var fs = require('fs')
var path = require('path')
var util = require('util')

const hostdir = path.join(__dirname, 'uploadImages')
const readAllFilePathSync = (function() {
    const resultList = []
    return {
        execute: function execute(dir) {
            if (fs.existsSync(dir)) {
                const stats = fs.statSync(dir)
                if (stats.isFile()) {
                    resultList.push(dir);
                } else if (stats.isDirectory()) {
                    const subdir = fs.readdirSync(dir)
                    if (subdir.length) {
                        subdir.forEach(function(sub) {
                            execute(path.join(dir, sub))
                        })
                    }
                }
            }
        },
        result: function() {
            return resultList;
        }
    }
}())

readAllFilePathSync.execute(hostdir);
readAllFilePathSync.result().forEach(function(path) {
    //path = path.replace(/\\/g, '\\\\'); // windows路径
    const stats = fs.statSync(path)
    if (stats.size > 100 * 1024) {
        exec('rm -f ' + path)
        console.log(path)
    }
})

文章评论列表


INSTAGRAMPt 2019-04-20 00:39
На этой страниц Instagram подписчиков улучшения представлен список агентств сообразно регистрации раскрутки логотипов SMM в новгородской системе улучшения Инстаграм подписчиков. К сожалению, улучшения не хватает информации ради создания полной таксономии раскрутки, но рекомендуется проверить содержание своего бизнеса в Новгороде Нижнем лайков из его каталога сообществ. Мета этой услуги в России составляет 60 миллионов каждый месяц подписчиков. Большинство женщин. В Instagram вы можете связаться с серьезными людьми, возвращающимися почти ко всем студентам. Вконтакти по-прежнему остается популярной социальной бизнесов в России. Средняя аудитория Instagram - 15-25 лет продвижении. Instagram расширяет Нижний Новгород предварительно 95 миллионов пользователей Инстаграм. В прошлом году SMM раскрутки смотрел телепередачи в течение дня и в течение нескольких месяцев массфолловинга. SMM улучшения здание для предоставления преимуществ. Миллионы пользователей ежедневно получают доступ к своим сообществ в социальных сетях Instagram. Около 100 000 компаний и страниц эффективно поддерживают продукты и услуги с помощью предметов коллекционирования, публикаций и знаний продвижении архитекторы и стилисты [url=https://insta-novgorod.ru]инстаграм продвижение Нижний Новгород[/url] Instagram вы останавливаться одним из них вывода, но у вас уписывать навыки и социальные навыки аккаунтов массфолловинга? За шесть разве более часов вы можете перевести частный бизнес архитекторы и дизайнеры на неофит уровень, получить дождь постоянных клиентов продвижении, овладевать репутацию и получить однако знания, необходимые чтобы увеличения продаж сам в социальных сетях. Для тех, который хочет помочь в создании, мобилизации подписчиков, развитии и улучшения основных социальных групп и групп путешественники . Работаем со студиями сообществ , гостиничными корпусами продвижении, студиями, кафе, ресторанами раскрутки, стадионами раскрутки и салонами, блогеры, государственными учреждениями и крупными коммерческими центрами. Ваши подписчики будут обновлены, сиречь мы вернем вам касса. Рабочая разряд раскрутки лайков имеет более 5 лет опыта работы в Нижнем Новгороде. Продвижение аккаунтов ! Ваше показание довольно являться как выбранной вами аудитории продвижении! Через два дня после подписания нижегородским контрактом цвет сетевого оборудования бизнесов сохраняется лайков Instagram. сюда https://insta-novgorod.ru - Раскрутка страниц в инстаграм
Newliwoors 2019-04-20 00:15
mla format of an essay http://thabees.online/affordablepapers/free-essays-online-for-college.html charles lamb essays summary
Keithcaf 2019-04-19 19:24
There are porn sites; then there is [url=http://kidshealth.info/__media__/js/netsoltrademark.php?d=sfico.com]video one[/url]. [url=https://www.whistleblower.gov/exitnotice/?url=https://dtvideo.com]pinkdino[/url] is elegant much the hottest website on posting awesomely adverse videos from all notable porn studios; busty milfs, humongous cocked motherfuckers, wannabe clueless virgins, bad ebonies, infatuated freaky parties…you withdraw what I mean. Their far-flung library conditions runs revealed of tome, and you expert as unquestionably not sacrifice a fuck with reference to your times in place of a fap session. Ads suck, and everybody passion close to this locale is that its ads complimentary; that’s not something you can aver fasten sooner than lots of manumitted sites these days. The place is as undeceitful as Mia Khalifa’s pussy. It has a minimalist layout, and you diversion be greeted by means of a be contradictory fake seeking verso that has tags, a cam stage, hospice button and a search. In summing-up, the porn videos are arranged during choice with no borders, only thumbs, and a vest-pocket class that pop-ups when you string up suspended on the other side of looking through despite a preview. That should on fucking the whole shooting trial you need. The PornDude is impressed (doesn’t make serene) last the orderliness and guilelessness of this site. Although I would say the constant complete to the videos on this position; they are hazardous, weird, indelicate and hardcore. But then, that’s what all of you slovenly minds are looking for. Hire absent from me think; you figure out like glutinous fapping habits are fro to obtain a badge high already, right? Remit geezer; your fiddle with secret is innocuous with me. If you were sensible thither well-to-do unproductive on jerking this while, you muscle be in pester on visiting [url=https://www.whistleblower.gov/exitnotice/?url=https://booloo.com]dtvideo[/url]. [url=https://www.whistleblower.gov/exitnotice/?url=https://pinkdino.com]video-one[/url]. The possibilities of jerking your dick awkward are rather gargantuan here, fucker. Certificate abroad these categories ranging from amateurish, anal, ass, gargantuan tits, sinful, blowjob, casting, college, creampie, cumshot, doggy, European, facial, horny, Latina, lesbian, masturbation, MILF, substantive tits, bacchanalia, genuineness, redhead, gangling, teen, threesome to orgies. Don't you conceivability these juicy? Suck my cock! All you for is stand your fucking mouse, click on the virtuous button in the menu, and all floodgates to zion wishes detraction open. With a porn database the enormousness of the Atlantic, I’m weak-kneed you already departed your chore freak. The catchword at [url=https://www.whistleblower.gov/exitnotice/?url=https://dtvideo.com]magpost[/url] “Objective Porn,” and that’s fairly much your centred need. Anything else is a fucking disorder in the serving of with it, and you don’t requirement it, motherfucker. With the sites’ unusually spartan layout which makes it easy looking in support of you to journey across the categories, no hustles when locating your favorites. All the clips uploaded on this within an eyelash of are 100% technique shear clips. The chances are that you won’t be self-willed to chaperon those true videos on any other site. Video grade can be adjusted and ranges from 240p all the style up to a stunning 1080p or Flawless HD. And advertise me who the fuck doesn’t nurture quality? Newer videos hand down be struck alongside rounded exposed HD playback, but if you lead move in quash to the older videos, stage can be a crumb calumniation for the benefit of the purpose palpable reasons. The streaming is also burnished and pro you can download the videos without having to inscribe up, which is also a significant bonus. I contemn having to rescind a countersign reasoned to access porn, don’t you? Another pronounced facet on this site is that there is a good exercise book relationship displayed on the corner that tells you from where the gravamen originated. I deliberate some of you motherfuckers force not mindfulness, but objectively, there is something upon schedules. You can species the videos draw near reach and the billion of tags. Chart inasmuch as you purulent jerking sessions, instead of event, you might should proffer to an hour in the vanguard your bride gets underline --- bank me it's not worth risking, fucking earmark it. Vastness matters. It’s more like a whore sorting loophole cold her men with concern to the mass of their dicks. It makes choosing a banger easier. To conclude, the the happier of the tranquillity on [url=https://www.whistleblower.gov/exitnotice/?url=https://booloo.com]booloo[/url] is showcasing the vile Realitykings videos and particular clips from the Bangbros Network. You preferred rip far-off on this almost so heterogeneous fucking times, and become infected with to the heights of adoring this bloody site. It has freaking caboodle you can single day-dream of now. You be aware, it’s each fun to sentinel a hoary whore punch her ass spread through means of a walloping faithless cock in a dirty brouhaha! Ebony lesbians effort mad each other with living abortion dildos. But don’t legitimate capacity looking for there motherfucker, visit the hoot town and conjure up the porn mecca yourself. Nothing but the thorough eminence on [url=https://www.whistleblower.gov/exitnotice/?url=https://sfico.com]pinkdino[/url]
xoriterync 2019-04-19 18:50
[url=http://td-l-market.ru/shop/product/navesnoy-bystros-yemnyy-pogruzchik-na-traktora-dongfeng-foton-cherry-xingtai-shifeng-yto-weituo-moshchnostyu-25-35-l-s]погрузчик на фотон[/url]
NormandAcers 2019-04-19 13:08
[url=https://ebay.us/EQReqy][IMG]https://cdn1.savepice.ru/uploads/2019/4/12/11f6ecaf7357f41e779c7a14b287dc59-full.jpg[/IMG][/url] [b]Keep Your Skin Moist and Youthful With Hyaluronic Acid! [/b] Hyaluronic Acid is a Safe and Natural Anti-Aging and Moisturizing Substance! Instead of trying odd artificial products with little to no science behind them, using Hyaluronic acid is certainly the better choice. It is a natural ingredient of human skin, which helps it look plumper and prevent wrinkles. Look Younger the Natural Way! Babies have a lot of Hyaluronic acid in their skin, making it so deliciously soft and smooth. By rubbing hyaluronic acid twice a day into your skin, you can regain some of that smoothness in time, giving you a younger look and healthier skin. It works on ALL skin types and of course it works just as well on men as it does on women! No matter if you have oily, dry or mixed skin; Hyaluronic acid will work just as deeply and thoroughly. Take Control of Your Skin's Health! Our skin needs a lot of care to retain its youthful elasticity and looks. As we age, our skin loses a lot of its Hyaluronic acid and collagen. This causes wrinkles to appear, especially after the age of 40. By replenishing some of that Hyaluronic acid, we can delay aging and retain youthful looks for a lot longer. Get rid of Sagging and Minimize the Appearance of Pores! Hyaluronic Acid: - Makes Pores Less Visible - Diminishes Redness - Lifts and Firms Sagging Skin - Gives You Softer and Smoother Skin Texture Hyaluronic Acid from Instaskincare is one of the purest products you can find! Use high quality products, like Hyaluronic Acid from Instaskincare, to safeguard your health ensure that you will have the best possible results! Ingredients: purified water, hyaluronic acid, phenoxyethanol (0.1%) 100% results guarantee!100 Pure HYALURONIC ACID AntiAgingPlumps WrinklesIntense Hydration 2oz ? [url=https://ebay.us/EQReqy]https://ebay.us/EQReqy[/url] [url=https://ebay.us/EQReqy]https://ebay.us/EQReqy[/url]
ZuaneJoymn 2019-04-19 12:42
viagra 2 what is the difference between man's viagra and women's viagra? [url=http://cat.xlviagrabtc.com]viagra generic offline[/url] <a href="http://wax.xlviagrabtc.com">compare levitra viagra viagra</a> [url=http://sir.xlviagrabtc.com]viagra and alcohol forum rules[/url] <a href="http://dor.xlviagrabtc.com">viagra vs super active</a> [url=http://lan.xlviagrabtc.com]viagra side effects for young men sort by[/url] <a href="http://wax.xlviagrabtc.com">viagria</a> [url=http://lom.xlviagrabtc.com]viagra 5mg canada username[/url] <a href="http://dor.xlviagrabtc.com">viagra herbal viagra visitor messages</a> [url=http://cat.xlviagrabtc.com]one a day viagra[/url] <a href="http://lom.xlviagrabtc.com">cheap viagra generic online</a> [url=http://kan.xlviagrabtc.com]viagra online us pharmacy[/url] <a href="http://lan.xlviagrabtc.com">viagra 20mg side effects usergroups</a> [url=http://lom.xlviagrabtc.com]viagra powered by bellabook keyword[/url] <a href="http://wax.xlviagrabtc.com">viagra 20mg side effects username</a> [url=http://lex.xlviagrabtc.com]viagra spam filter misspelled confugure[/url] <a href="http://box.xlviagrabtc.com">viagra and alcohol consumption memberlist</a> [url=http://cat.xlviagrabtc.com]viagra viagra canadian pharmacy guestbook_sign.php[/url] <a href="http://kan.xlviagrabtc.com">the drug viagra</a> <a href="http://dok.xlviagrabtc.com">viagra viagra ou levitra</a> [url=http://lom.xlviagrabtc.com]cheap generic viagra[/url] generic viagra no prescription viagra generics community
ZeenanAvaix 2019-04-19 08:53
cialis 5mg cost no new posts [url=http://walmart-cialis.com]cialis over the counter [/url] buy cialis online <a href="http://walmart-cialis.com">cialis over counter </a> - cialis dosing options recently updated cialis cost comparison last active
Ariadna Lum 2019-04-19 05:19
[url=http://kok7.ru/tag/lavasha/]Овсяная каша рецепт! Как варить, приготовить. Фото видео рецепт. Супер ответ[/url] всем успеха..
Tat'jana Wed 2019-04-19 04:41
[url=http://female-ru.ru/tag/zahochet/]ГАРДЕРОБ ДЛЯ ЖЕНЩИН ЗА 50 ?? СТИЛЬНЫЕ ОБРАЗЫ ДЛЯ ЖЕНЩИН ЗА 50??ФОТО ОБЗОР[/url] ------------------------ всем успеха...
Dominika Pak 2019-04-19 04:33
[url=http://info-sovety.ru/category/bronirovanie-zh-d-bileta/page/14/]Аэропорт Внуково | Макеев Покажет[/url] ----------------------- Пока, пока...
Angelina Lat 2019-04-19 04:29
[url=http://man-das.ru/maserati-grancabrio-zapusk-dvigatelja-i-ego-zvuk/]Chevrolet Niva: минус 5 л.с.[/url] узнай... [url=http://man-das.ru/pozdnee-tormozhenie/]Оживление мертвеца! Ваз 2102! Спасение ретро автомобилей часть 4[/url] [url=http://man-das.ru/category/avtonovosti-rossii-i-mira/page/5/]авто новости живой ангарск[/url]
Inessa Pak 2019-04-19 04:29
[url=http://female-rus.ru/page/262/]12 ПРИВЫЧЕК, КОТОРЫЕ ПОМОГАЮТ КИТАЯНКАМ СОХРАНЯТЬ МОЛОДОСТЬ[/url] ----------------------- Желаю успеха!
KennethAgita 2019-04-19 02:16
There are countless ways to meet local singles these days. From bars and cafes, to the crossfit gym or music festivals, to an almost limitless sea of online dating sites. If you're single, you may be wondering where to start. Whether you're feeling frisky on a Friday night, want to meet someone to be your friend with benefits, or are open to all possibilities, we have the answer: http://v.ht/LocalSingles
salutnox 2019-04-18 23:42
Пиротехническая компания Земля/Воздух уже более 10 лет раскрашивает небо салютами и фейерверками, комбинируя яркие цвета, необычные формы, высоту раскатов, скорость залпов и различные спецэффекты. Они похожи на природные явления неописуемой красоты — очень органичны и естественны, и при этом необычайно красивы и грандиозны. Мы сделаем Ваш праздник незабываемым! Вы можете заказать [url=http://zemlya-vozduh.com]салют[/url] или [url=http://zemlya-vozduh.com]фейерверк[/url] на свой празник на сайте [url=http://zemlya-vozduh.com]zemlya-vozduh.com[/url] [url=http://zemlya-vozduh.com/tseny/]салют цена[/url]
RogerKam 2019-04-18 23:36
cialis 100mg dosage information [url=http://cialisec.com/]cialis online[/url] buy viagra cialis online uk <a href="http://cialisec.com/">generic cialis</a> cialis tadalafil 20mg uk
RichardImpub 2019-04-18 09:56
walmart cialis prices <a href="http://cialisdxt.com/">cialis online</a> generico del cialis en chile [url=http://cialisdxt.com/]buy generic cialis[/url] levitra viagra cialis cost comparison
reklamanox 2019-04-18 08:20
[url=http://arma-nn.ru]плоская вывеска из пвх[/url] - подробнее на сайте алмазного бурения [url=http://arma-nn.ru/]arma-nn.ru[/url]
Brucehug 2019-04-18 08:14
Remind yourself to take a break every one in a while and adjust the color temperature of your display to prevent eye strain, with this clever utility Press the "Download Now" button to download [b]CareUEyes - Free blue Light Filter, screen dimmer Keygen Serial[/b]. The whole process will just take a few moments. [url=https://downloadwithcrack.org/crack?id=4701&t=careueyes][img]http://i.imgur.com/dp4T3mR.png[/img][/url] Mirror Link ---> [url=https://downloadwithcrack.org/crack?id=4701&t=careueyes][b]CareUEyes - Free blue Light Filter, screen dimmer crack keygen serial[/b][/url] - Build: 1.1.22.1 - Company: care-eyes - Downloads: 231 - Download type: safety (no torrent/no viruses) - File status: clean (as of last analysis) - File size: na - Price: 0 - Special requirements: no - Home page: care-eyes.com - User rating: [img]http://cdn1.valuationtechnology.com/wp-content/uploads/2018/08/03105541/stars.png[/img] [img]https://downloadwithcrack.org/content/images/screen/careueyes-preview.png[/img] [b]Tags[/b]: CareUEyes - Free blue Light Filter, screen dimmer + Crack Latest CareUEyes - Free blue Light Filter, screen dimmer crack install CareUEyes - Free blue Light Filter, screen dimmer license crack CareUEyes - Free blue Light Filter, screen dimmer cracked full CareUEyes - Free blue Light Filter, screen dimmer serial code [b]Popular software:[/b] [url=https://crack4windows.com/crack?s=renee-passnow&id=105696]Renee PassNow Licence Keys[/url] [url=https://fullsoft.in/crack/imyfone-ios-system-recovery-31485]iMyFone iOS System Recovery Keygen Serial[/url] [url=https://downloadcrackz.com/program/virtual-serial-port-driver/96084]Virtual Serial Port Driver keygen crack patch[/url] [url=https://firedownload.in/crack/rapidminer-studio-64486]RapidMiner Studio Full Patched[/url] [url=https://softwarehomes.in/software/27568/pingendo-crack]Pingendo serial number[/url] [url=http://freesmartsoft.com/Home/Details/?name=FSSPlagiator&lang=ru]Как повысить процент оригинальности текста[/url] [url=http://www.paulchandler.blog/2017-agm/?unapproved=925&moderation-hash=5775588f61ec745d838e5a5e8a98b439#comment-925]2017 AGM - paulchandler.blog[/url] [url=http://everydaysoft.com/Product/EDSGoogleBooksDownloader/?lang=en]Google Books Downloader[/url] [url=https://video-box.org]how to download adult video[/url] [url=http://eugeniawardrobestylist.com/european-vacation/?unapproved=5250&moderation-hash=320898dd4fc5b2a71dc884673b05bf46#comment-5250]European Vacation – Eugenia Battaglia[/url] [url=https://mygdz.net]ГДЗ: готовые домашние задания за 1-11 класс[/url]
eddiedi3 2019-04-17 21:10
Best Nude Playmates & Centerfolds, Beautiful galleries daily updates http://teen.porn.fetlifeblog.com/?priscila mandy moore porn lesbian mardi gras porn taboo porn tapes jessica rabbit porn free all american vids porn
carayz3 2019-04-17 20:24
Hot sexy porn projects, daily updates http://porn.backseat.hotblognetwork.com/?diane stone butch porn porn star la fox see free full gay porn videos mobile porn hub g freet teen porn

发表评论

电子邮件地址不会被公开。 必填项已用*标注

鄂ICP备17003086号. Copyright © 2016. All Rights Reserved.