node-js 异步处理图片,异步处理json文本

本文介绍了如何使用Node.js进行异步操作,包括图片的重命名并复制到指定目录,以及JSON文件内容的解析与更新。通过示例展示了如何利用fs模块处理图片和读写文件,以及如何使用Promise链管理并发任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 node-js 异步处理图片,异步处理json文本

var path = require("path");
var fs = require("fs");
//创建目录
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}
let outdir = path.join(__dirname, 'out');
mkdirsSync(outdir);
/** 赋值复制移动 A to B */
function copyFile(fromUrl, outUrl) {
    let file = fs.createReadStream(fromUrl);
    let out = fs.createWriteStream(outUrl);
    file.pipe(out);
}

/** 重新命名 */
function rename(oldName) {
    let newName = '';
    let names = oldName.split(".")
    for (let i = 0; i < names[0].length; i++) {
        if (/^[a-zA-Z]*$/.test(names[0][i])) {//有字母,已取得的字符串清零从来
            newName = '';
        } else {
            newName += names[0][i];
        }
    }
    newName = Number(newName) - 6444;//重命名,8000->1556
    if (names[1]) {
        return `RND${newName}.${names[1]}`;
    }
    return `${newName}`;
}

// __dirname 当前工作目录 
/** 处理图片 和 json文件 */
var dirPath = path.join(__dirname, "img");
let fileNames = fs.readdirSync(dirPath);
let pngArr = [];
let jsonArr = []
for (let i = 0; i < fileNames.length; i++) {
    let extname = path.extname(path.join(dirPath, fileNames[i]));
    if (extname == ".png") {//处理图片,重命名,并复制到一个新的路径下
        pngArr.push(fileNames[i]);
    } else {
        jsonArr.push(fileNames[i]);
    }
}
let __time = new Date().getTime();
let _png = 0;
let _json = 0;
/** 异步执行复制图片,一个图片复制完成了再执行下一个图片的处理 */
var copyPngfile = () => {
    let pngName = pngArr[_png];
    if (!pngName) {
        console.log(`共处理文件${_png + _json}个,png文件${_png}个。总耗时: ${new Date().getTime() - __time}`);
        return;
    }
    let _time = new Date().getTime();
    let newName = rename(pngName);
    let file = fs.createReadStream(path.join(dirPath, pngName));
    let out = fs.createWriteStream(path.join(outdir, newName));
    out.on("finish", () => {
        console.log("Png 耗时: ", new Date().getTime() - _time, "   总耗时: ", new Date().getTime() - __time);
        _png++;
        copyPngfile();
    })
    file.pipe(out);
}
copyPngfile();

/** 异步处理文件,一个文件处理完成后再去处理另外一个文件 */
var copyOtherfile = () => {
    let fileName = jsonArr[_json];
    if (!fileName) {
        console.log(`共处理文件${_png + _json}个,无后缀json${_json}个。总耗时: ${new Date().getTime() - __time}`);
        return;
    }
    let newName = rename(fileName);
    let _time = new Date().getTime();
    fs.readFile(path.join(dirPath, fileName),  "utf-8", (err, res) => {
        let content;
        try {
            content = JSON.parse(res);
            content.name = `#VCR ${newName}`;
            content.image = `https://d9lekpvd0q3e4.cloudfront.net/img/RND${newName}.png`
        } catch(e) {
            content = res;
        }
        fs.writeFile(path.join(outdir, newName), JSON.stringify(content), "utf-8", (err) => {
            if (err) {
                console.error(err);
            }
            console.log("Other 耗时: ", new Date().getTime() - _time, "   总耗时: ", new Date().getTime() - __time);
            _json++;
            copyOtherfile();
        });
    })
}
copyOtherfile();

json 文件 8000.json

{"name":"#VCR 8000","description":"We aim to be the Top crypto poker platform.The LIMITED collection of 10,000 unique NFTs  will be the key to bond the community. The full version game itself will be launched no less than Q3 2022 with profit sharing scheme.","attributes":[{"trait_type":"background","value":"1"},{"trait_type":"behind","value":"24 "},{"trait_type":"body","value":"Franky"},{"trait_type":"expression","value":"Franky1"},{"trait_type":"tie","value":"necklace 8"},{"trait_type":"coat","value":"1"},{"trait_type":"hair","value":"1"},{"trait_type":"hand","value":"1"},{"trait_type":"hand-hold","value":"1"}],"image":"https://d9lekpvd0q3e4.cloudfront.net/img/RND8000.png"}

图片8000.json

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值