0

I use the following code to read json files from my node application folder. I've folder with json files and I want to read the content with the following code the proj built like following

myproj
  folder1
     file1
  jsonFiles
    json1.json

now from file1 I want to get json1,I try with the following which doesnt work..any idea?

 glob("jsonFiles/*.json", function(err, files) { 

            files.forEach(function(file) {
                fs.readFile(file, 'utf8', function (err, data) {
                 console.log("im here")

Im not able to reach the "im here" in the console,what it can be ? when I put Break-point I able to see get to fs.readFile but in the next line it doesnt stops and I dont get any error... UPD

in debug I see in file fs.readFile(file, 'utf8', the following path:jsonFiles/json1.json

  • First, `files.forEach` is synchronous and you're calling an async method inside it. It won't work the way you expect. Second: it's `consloe.log` in your code or it's just a typo in the code snippet? – Rodrigo Medeiros Jul 13 '15 at 13:34
  • And you should also log the `err` to see what's going on. – Rodrigo Medeiros Jul 13 '15 at 13:35
  • @RodrigoMedeiros -Thanks this is typo :) but what should I do to make it work? I put if(err) instead of the err but I dont get any error since its not jumping to the next line(in debug mode) –  Jul 13 '15 at 13:46
  • http://stackoverflow.com/help/mcve – Petr Skocik Jul 13 '15 at 14:03

1 Answers1

0

It works just fine:

$ touch 1 2 3

$ cat > app.js
var fs = require('fs');
var files = ['1', '2', '3'];
files.forEach(function(file) {
    fs.readFile(file, 'utf8', function (err, data) {
     console.log("im here");
    });
});
^D

$ nodejs app.js
im here
im here
im here
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Thanks but this is not helping since I try to do it on files inside my project... –  Jul 13 '15 at 14:07
  • in debug I see in file fs.readFile(file, 'utf8', the following path:jsonFiles/json1.json –  Jul 13 '15 at 14:13
  • 1
    You can `mkdir jsonFiles`, `touch jsonFiles/json{1,2,3}.json` and replace the files `files` array in the *.js file with `[ 'jsonFiles/json1.json' ...` and it still works. Your problem is most likely in that that glob doesn't call you back with the `files` you expect. Log it to see what `files` you're getting before you call forEach on it. – Petr Skocik Jul 13 '15 at 14:23
  • Thanks but what do you mean with mkdir jsonFiles, touch jsonFiles/json{1,2,3}.json can you provide example in your answer? –  Jul 13 '15 at 14:28
  • That's just basic command lines stuff for creating the directory and the files that the node script will try to read from. – Petr Skocik Jul 13 '15 at 14:35
  • 1
    I think that this is related to glob I accept your answer and I've additional question now maybe you can help :) http://stackoverflow.com/questions/31386539/how-to-use-code-in-node-js-just-one-time-for-application –  Jul 13 '15 at 14:47