Node.js读取某个目录下的所有文件夹名字并将其写入到json文件


针对解决的问题是,有些时候我们需要读取某个文件并将其写入到对应的json文件(xml文件也行,不过目前用json很多,json是主流)。

源码如下:
index.js

var fs = require('fs');

let components = []
const files = fs.readdirSync('./')
files.forEach(function (item, index) {
    let stat = fs.lstatSync("./" + item)
    if (stat.isDirectory() === true) { 
      components.push(item)
    }
})

console.log(components);

let str = JSON.stringify(components)
 
 fs.writeFile('./extension.json',str,function(err){
 if (err) {res.status(500).send('Server is error...')}
})

控制台输出对应的数据:

参考资料如下:
nodejs写入json文件,格式化输出json的方法:http://www.cnblogs.com/threeEyes/p/10023827.html
利用nodejs对本地json文件进行增删改查:https://blog.csdn.net/zhaoxiang66/article/details/79894209


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM