Node JS Файл пуст после чтения - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь регистрировать местоположение твитов в отдельном JSON файле для каждого идентификатора Twitter, который я просматриваю. Следующий код вызывается для каждого твита и должен создавать новый JSON файл для каждого нового идентификатора и добавлять местоположение текущего твита:

console.log("@" + tweet.user.screen_name + " - " + tweet.user.name);
    
    timeStampNow = "[" + date.getDate() + ":" + date.getMonth() + ":" + date.getFullYear() + "-" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]";
    
    console.log(timeStampNow + " " +  tweet.place.full_name);
    
    fs.exists(userData + "/" + tweet.user.id + ".json", function(exists) {

      //Is executed if file does not Exists
      if (!exists){
        console.log("Person Not Recognised. Adding to Folder");
        json = {};
        json.user = tweet.user;
        json.locations = [];
        
        fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(json), 'utf8', function(err) {
          if (err) throw err;
          console.log('complete'); 
        });
      }

      //Appends data to file
      fs.readFile(userData + "/" + tweet.user.id + ".json", function (err, data) {
        var readJSON = JSON.parse(data);
        console.log(readJSON);

        locationJSON = {};
        locationJSON.time = timeStampNow;
        locationJSON.geo = tweet.geo;
        locationJSON.coordinates = tweet.coordinates;
        locationJSON.place = tweet.place;
        
        readJSON.locations.push(locationJSON);
        fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(readJSON), 'utf8', function(err) {
          if (err) throw err;
          console.log('complete'); 
        });
      });

    });

Первая часть скрипта работает без проблем, но Часть, которая должна добавлять текущее местоположение к JSON файлу, иногда делает файлы пустыми, что приводит к ошибке:

undefined
^

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at ReadFileContext.callback (C:\path\to\Program.js:44:29)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:257:13)

Вот пример того, как JSON должен выглядеть в конце:

{
    "user":{
        "id":"877id920012",
        "id_str":"id_str",
        "name":"name",
        "screen_name":"screen_name",
        "location":"location",
        "url":"url",
        "description":"description",
        "translator_type":"translator_type",
        "protected":"protected",
        "verified":"verified",
        "followers_count":"followers_count",
        "friends_count":"friends_count",
        "listed_count":"listed_count",
        "favourites_count":"favourites_count",
        "statuses_count":"statuses_count",
        "created_at":"created_at",
        "utc_offset":"utc_offset",
        "time_zone":"time_zone",
        "geo_enabled":"geo_enabled",
        "lang":"lang",
        "contributors_enabled":"contributors_enabled",
        "is_translator":"is_translator",
        "profile_background_color":"profile_background_color",
        "profile_background_image_url":"profile_background_image_url",
        "profile_background_image_url_https":"profile_background_image_url_https",
        "profile_background_tile":"profile_background_tile",
        "profile_link_color":"profile_link_color",
        "profile_sidebar_border_color":"profile_sidebar_border_color",
        "profile_sidebar_fill_color":"profile_sidebar_fill_color",
        "profile_text_color":"profile_text_color",
        "profile_use_background_image":"profile_use_background_image",
        "profile_image_url":"profile_image_url",
        "profile_image_url_https":"profile_image_url_https",
        "profile_banner_url":"profile_banner_url",
        "default_profile":"default_profile",
        "default_profile_image":"default_profile_image",
        "following":"following",
        "follow_request_sent":"follow_request_sent",
        "notifications":"notifications"
    },
    "locations":[
        {
            "time":"time",
            "geo":"geo",
            "coordinates":"coordinates",
            "place":{
                "id": "id",
                "url": "url",
                "place_type": "place_type",
                "name": "name",
                "full_name": "full_name",
                "country_code": "country_code",
                "country": "country",
                "bounding_box": {
                     "type": "type",
                     "coordinates": "coordinates"
                },
                "attributes": {}
              }
        }
    ]
}

1 Ответ

1 голос
/ 06 августа 2020

fs.writeFile и файл чтения - это асинхронная операция c. Когда вы создаете файл, он также может попытаться прочитать файл, который еще не был создан, поэтому вы получите неопределенные данные. На боковой заметке проверьте ошибки

console.log("@" + tweet.user.screen_name + " - " + tweet.user.name);
    
    timeStampNow = "[" + date.getDate() + ":" + date.getMonth() + ":" + date.getFullYear() + "-" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]";
    
    console.log(timeStampNow + " " +  tweet.place.full_name);
    
    fs.exists(userData + "/" + tweet.user.id + ".json", function(exists) {

      //Is executed if file does not Exists
      if (!exists){
        console.log("Person Not Recognised. Adding to Folder");
        json = {};
        json.user = tweet.user;
       
        locationJSON = {};
        locationJSON.time = timeStampNow;
        locationJSON.geo = tweet.geo;
        locationJSON.coordinates = tweet.coordinates;
        locationJSON.place = tweet.place;
        json.locations = [locationJSON];
        fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(json), 'utf8', function(err) {
          if (err) throw err;
          console.log('complete'); 
        });
      }else{
          fs.readFile(userData + "/" + tweet.user.id + ".json", function (err, data) {
        var readJSON = JSON.parse(data);
        console.log(readJSON);

        locationJSON = {};
        locationJSON.time = timeStampNow;
        locationJSON.geo = tweet.geo;
        locationJSON.coordinates = tweet.coordinates;
        locationJSON.place = tweet.place;
        
        readJSON.locations.push(locationJSON);
        fs.writeFile(userData + "/" + tweet.user.id + ".json", JSON.stringify(readJSON), 'utf8', function(err) {
          if (err) throw err;
          console.log('complete'); 
        });
      });
      
      }

      //Appends data to file
    

    });

, перед выполнением любой операции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...