【问题标题】:Put json file content in an array unsing node JS使用节点 JS 将 json 文件内容放入数组中
【发布时间】:2017-10-07 18:18:01
【问题描述】:

所以我有一个目录,其中有几个以“创建日期和时间”.JSON 命名的 Json 文件。我想创建一个包含所有json内容的数组,意思是

FIle1.json

文件 2。 json . . . FIlen.json

应该看 [{FIle1.json (content)}, {File2.json},......{Filen.json}]

我是 Node.json 的新手,欢迎任何帮助

更新

所以我列出了我的文件,现在我无法成功打开它们,下面是我的代码:

const testFolder = './report/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
    fs.readFile(file, {encoding: 'utf-8'}, function(err, data){
      if (err) {
            console.log(err);
            throw err;
        }
       console.log('result read: ' + data);
    });
  });
})

结果我得到: 我列出了文件:

revision_2017-04-19T16:26:33+02:00.json revision_2017-04-19T16:27:25+02:00.json

然后当我想打开它们时:

{ [错误:ENOENT:没有这样的文件或目录,打开 'revision_2017-04-19T16:26:33+02:00.json'] 错误号:-2,代码: 'ENOENT',

有没有人想办法解决这个问题?

谢谢大家

【问题讨论】:

  • 你走了多远?你知道如何在 Node.js 中打开和读取文件吗?
  • 我仍然不知道如何读取和打开文件。我对 node.js 真的很陌生
  • 我认为你应该在这种情况下分解问题。在您知道如何打开和读取文件之前,询问连接 JSON 数组是没有意义的。
  • 是的。我现在可以列出我所有的文件,现在我想我需要一个一个打开它们
  • 我有一个问题,如何阅读我获得的文件列表的内容?

标签: json node.js promise bluebird node-modules


【解决方案1】:

你要做的是列出你目录中的所有文件,然后将它们全部打开并将它们的内容放在一个对象中。

为此,您可以使用fs 模块(文件系统)列出并打开所有文件,然后将内容放入数组中:

const fs = require('fs');
let myArray = [];
fs.readdir('./your_directory', (err, files) => { // return an array that contains the names of the files in 'your_directory'
  files.forEach(file => { // loop over your files
    fs.readFile(file, {encoding: 'utf-8'}, function(err, data){ // open each file
      // the data variable represents your JSON file
      myArray.push(JSON.parse(data));  
    });
  });
});

到了这里,但你可能想回到主 js 作用域,所以你可以使用 Promises,或者使用以下方法:

  • fs.readFileSync
  • fs.readdirSync

它们执行与前面的函数(readFile / readdir)相同的操作,但是是同步的。

希望对你有帮助,
最好的问候,

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多