【问题标题】:Read json files from folder using require node module使用 require 节点模块从文件夹中读取 json 文件
【发布时间】:2019-03-27 13:23:36
【问题描述】:

我正在尝试在我的应用程序中使用循环读取所有 json 文件。 这是读取单个文件的代码,运行良好。

 const translations = require("../data/hello" + fileEndWith);

但是目录翻译中有10多个文件,所以我不想为每个文件编写相同的代码,而是想循环读取。

let fs = require('fs');

let fileEndWith = "en.json";


fs.readdir("../data/", (err, fileNames) => {
    fileNames.forEach((fileName) => {
        if(fileName.indexOf(fileEndWith) != -1){
            // some code.....
        }
    });
});

但它给出错误,无法解析 fs。

【问题讨论】:

标签: angularjs node.js


【解决方案1】:

您可以使用来自cutie-fs 库的过程:

fs.readdir("../data/", (err, fileNames) => {
  let jsonFileNames = fileNames.filter(fileName => fileName.indexOf(fileEndWith) != -1);
  readDataFromFiles(jsonFileNames, {encoding: 'utf8'}, (error, dataObj) => {
    console.log(dataObj); // {fileName1: data1, fileName2: data2, ... } 
  });
});

readDataFromFiles 是下面的函数

const readDataFromFiles = (files, options, callback) => {
  let contents = {};
  let count = 0;
  if (files.length === 0) {
   callback(null, contents);
  }
  files.forEach(file => {
    fs.readFile(file, options, (error, data) => {
      if (error) {
        callback(error);
      } else {
        contents[file] = data;
        count += 1;
        if (count === files.length) {
          callback(null, contents);
        }
      }
    });
   });
 }

这个功能你可以找到here

另外,最好将const 用于模块: const fs = require('fs');

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2013-04-10
    • 1970-01-01
    • 2017-02-28
    • 2013-08-02
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多