js遍历文件生成json配置模板

内容基于这篇博客修改而来
链接:https://blog.csdn.net/younglao/article/details/77046830

在项目开发过程中,经常会需要根据项目资源和逻辑代码生成json,我上附的博客可以很好的做到这件事。其实就是在文件夹和文件case上走不同的逻辑,因此搬运过来,便于查看

ps:介绍一个文件读写转码很方便的nodejs包:iconv-lite
使用方法:

const iconv = require('iconv-lite');
//data_buffer指fs.readFile直接读出来的二进制数据流
//target_file_mode指编码格式,不同于原生的fs指支持几种编码方式,这个库支持编码方式有很多
//搬运库源码附上的支持编码方式
## Supported encodings

// *  All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex.
// *  Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap, utf32, utf32-le, and utf32-be.
// *  All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, 
//    IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. 
//    Aliases like 'latin1', 'us-ascii' also supported.
// *  All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP.

//编码
<data_buffer> iconv.encode(<string>, <target_file_mode>);
//解码
<string> iconv.decode(<data_buffer>, <target_file_mode>)

附上原文的代码:

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

//解析需要遍历的文件夹,我这以E盘根目录为例
var filePath = path.resolve('E:');

//调用文件遍历方法
fileDisplay(filePath);

/**
 * 文件遍历方法
 * @param filePath 需要遍历的文件路径
 */
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.Stats对象
                fs.stat(filedir,function(eror,stats){
                    if(eror){
                        console.warn('获取文件stats失败');
                    }else{
                        var isFile = stats.isFile();//是文件
                        var isDir = stats.isDirectory();//是文件夹
                        if(isFile){
                        	//这里需要做json生成的处理
                            console.log(filedir);
                        }
                        if(isDir){
                            fileDisplay(filedir);//递归,如果是文件夹,就继续遍历该文件夹下面的文件
                        }
                    }
                })
            });
        }
    });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值