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