Node.js爬虫下载图片(解决0字节图片问题)

downImg(remote, local) {
            const mkdir = (absLocal) => {
                if (fs.existsSync(absLocal)) {
                    return true;
                } else {
                    if (mkdir(path.dirname(absLocal))) {
                        fs.mkdirSync(absLocal, 0o777);
                        return true;
                    }
                }
            }
            return new Promise(resolve => {
                let root = path.join(path.dirname(process.cwd()), local);
                mkdir(path.dirname(root));
                request({ url: remote, encoding: null }, (err, response, body) => {
                    fs.writeFileSync(root, body, { encoding: 'binary' });
                    resolve();
                })
            })
        }

 

posted @ 2018-06-22 16:17  yudis  阅读(857)  评论(0编辑  收藏  举报