• nodejs脚本-将网络图片转成base64码方便写md插图


    #!/usr/bin/node
    
    'use strict';
    
    const HELP = `
    /***********************README***************************
     * 适用环境:Ubuntu18.04
     * 
     * 脚本所需模块:
     *  Node原生模块:fs、child_process
     *  第三方模块:http、https、clipboard(可选)
     * 
     * 其中fs用于生成临时文档文件以免字符过多时可查看文档
     * 其中child_process用于执行linux命令,搭配clipboard模块适用
     * 其中clipboard模块用于粘贴文本到剪贴板中
     * 安装:sudo npm install -g clipboard-cli
     * 
     * 支持网络图片格式:
     * 	jpg,png,webp,svg
     * 
     * 支持本地图片格式:
     * 	jpg,png,webp,svg
     * 
     * 脚本支持参数:
     *  -v, --version 	查看版本
     *  -t, --test		拉取网络示例图片测试
     *  -h, --help		查看帮助文档
     * 
     * 临时文件存放格式:
     * /tmp/img2base64-[DateTime]
     * 
     * 报错处理:
     * throw errnoException(err, 'spawn');
     * Error: spawn E2BIG
     * 
     ********************************************************/
     `
    const VERSION = '1.0-alpha';
    const AUTHOR = 'Chanj Wang';
    const DATE = '2020-05-13 AM'
    const PRINTINFO = `Img2Base64 version is: ${VERSION} by ${AUTHOR} at ${DATE}`;
    
    var fs = require('fs');
    var http = require('http');
    var https = require('https');
    var exec = require('child_process').exec;
    
    var httpModule = {http: http, https: https};
    var argv = global.process.argv;
    
    const READFROMWEB = 0;
    const READFROMLOCAL = 1;
    const TMPFILE = "/tmp/img2base64-"
    const FILENAME = TMPFILE + new Date().toJSON().replace(/:|./g, "-");
    
    var readmode;
    var imgUrl = "";
    var imgHttpType = "";
    var imgType = "";
    
    if (/^-+w+$/.test(argv[2])) {
    	switch (argv[2].match(/w+/)[0]) {
    		case 'v':
    		case 'version':
    			console.log('x1B[32m%sx1B[39m', PRINTINFO);
    			return;
    		case 'h':
    		case 'help':
    			console.log('x1B[33m%sx1B[0m', HELP);
    			return;
    		case 't':
    		case 'test':
    			imgUrl = 'http://www.baidu.com/img/baidu_jgylogo3.gif';
    	}
    } else {
    	imgUrl = argv[2];
    }
    
    if (/^http(s)?:///.test(imgUrl)) {
    	readmode = READFROMWEB;
    	imgHttpType = imgUrl.match(/^(w+):/)[1];
    } else {
    	readmode = READFROMLOCAL;
    }
    
    imgType = getImgType(imgUrl);
    
    if (readmode == 0) {
    	getBase64FromWeb(imgHttpType, imgUrl, imgType);
    } else {
    	getBase64FromLocal(imgUrl, imgType);
    }
    
    
    function execCommand(Command) {
    	exec(Command, function(err, stdout, stderr) {
    		if (err || stderr) {
    			console.error("
    复制到剪贴板失败!请直接查看上面路径文档进行复制");
    			return;
    		}
    		
    		console.log("
    复制到剪贴板成功!");
    	})
    }
    
    function converseImgBase64WithPrefix(ImgType, Base64String) {
    	var imgBase64ForMarkdown = "data:image/" + ImgType + ";base64," + Base64String;
    	
    	return imgBase64ForMarkdown;
    }
    
    function getImgType(Url) {
    	var type = (Url.match(/.(w+)$/) && Url.match(/.(w+)$/)[1]) || "jpg";
    	
    	if (type === "svg") {
    		type += "+xml";
    	}
    
    	return type;
    }
    
    function writeStream(Data, Filepath) {
    	return new Promise((resolve, reject) => {
    		var writerStream = fs.createWriteStream(Filepath);
    	
    		writerStream.write(Data, 'UTF8');
    		
    		writerStream.end();
    		
    		writerStream.on('finish', function() {
    			console.log("临时文件写入完成,文件路径: ", Filepath);
    			resolve(1);
    		});
    		
    		writerStream.on('error', function(err){
    			console.log(err.stack);
    			reject(0);
    		});
    	})
    }
    
    function getBase64FromWeb(HttpType, Url, ImgType) {
    	httpModule[HttpType].get(Url, function(res){
    		var chunks = [];
    		var size = 0;
    	
    		res.on('data', function(chunk){
    			chunks.push(chunk);
    			size += chunk.length;
    		})
    	
    		res.on('end', function(err){
    			var imgData = Buffer.concat(chunks, size);
    
    			var imgBase64 = imgData.toString("base64");
    	
    			var imgBase64ForMarkdown = converseImgBase64WithPrefix(ImgType, imgBase64);
    	
    			writeStream(imgBase64ForMarkdown, FILENAME)
    				.then(() => {
    					var cmd = 'cat ' + FILENAME + ' | clipboard';
    					execCommand(cmd);
    				})
    				.catch(() => {
    					console.error('文件写入失败')
    				});
    		})
    	})
    }
    
    function getBase64FromLocal(Url, ImgType) {
    	var imgData = fs.readFileSync(Url);
    
    	var imgBase64 = Buffer.from(imgData).toString('base64');
    
    	var imgBase64ForMarkdown = converseImgBase64WithPrefix(ImgType, imgBase64);
    	
    	writeStream(imgBase64ForMarkdown, FILENAME)
    		.then(() => {
    			var cmd = 'cat ' + FILENAME + ' | clipboard';
    			execCommand(cmd);
    		})
    		.catch(() => {
    			console.error('文件写入失败')
    		});
    }
    
  • 相关阅读:
    SQL Server 2008 Windows身份验证改为混合模式身份验证
    SQL中给datetime类型变量赋值
    结婚三周年特此@Mark一下
    搞笑的【国庆出游五大注意事项】
    利用SVNListParentPath增加http浏览仓库根目录的功能
    如果年底买不到CC就出手小指吧
    svn备份策略
    缺乏配置管理造成的常见问题
    高速公路开车必看的注意事项
    山雨欲来踏上Java学习之路
  • 原文地址:https://www.cnblogs.com/hencins/p/12794469.html
Copyright © 2020-2023  润新知