0

I have a movie-finding app that makes API calls in the backend. During initialization I need to load some JSON files: one (lang.json) contains a list of languages for searching purposes, the other (stored in the config variable) is used to get a link to the movie poster.

How would I ensure the loading of these files is completed before an HTTP request is made? One solution I can think of involves putting the calls to app.get() and app.listen() inside fs.readfile()'s callback. But is there a better way? Web development is totally new to me.

var express = require('express');
var app = express();
var fs = require('fs');
var request = require('request');
var merge = require('merge');

require('dotenv').config();

var apiKey = process.env.API_KEY;
var config = {};

app.use(express.static('view'));

// TODO load config and lang before below code

app.get('/lang', function(req, res) {
    fs.readFile('lang.json', function(err, data) {
        if (err) throw err;
        res.json(JSON.parse(data));
    });
});

app.get('/genres', function(req, res) {
    request.get({
        url: 'http://api.themoviedb.org/3/genre/movie/list',
        qs: {api_key: apiKey}
    }, function(error, response, body) {
        res.json(JSON.parse(body).genres);
    });
});

app.get('/randomMovie', function(req, res) {
    request.get({
        url: 'https://api.themoviedb.org/3/discover/movie',
        qs: merge(req.query, {api_key: apiKey})
    }, function(error, response, body) {
        body = JSON.parse(body).results;
        var len = body.length;
        var i = Math.floor(Math.random() * len);
        var movie = body[i];
        // movie.poster_path = movie.images.base_url + movie.images.poster_sizes[6] + movie.poster_path;
        res.json(movie);
    });
});

app.listen(3000, function() {
    console.log('server started on port 3000');
});
1
  • Why don't you load the file outside the app.get function? Commented Aug 9, 2016 at 5:30

1 Answer 1

1

The easiest way is to just use fs.readFileSync() before your call to app.listen(). For example:

var lang = fs.readFileSync('lang.json');

app.get('/lang', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(lang);
});

// ...

Just be aware that the contents of lang will not automatically update if the contents of lang.json change on disk during the lifetime of your node process.

Sign up to request clarification or add additional context in comments.

2 Comments

How's the performance hit from using a synchronous loading method? My app has already slowed considerably ever since I moved the API calls from client to server-side.
The performance hit is irrelevant since it'd only be done once at startup, before you start listening for requests. As far as performance of your external requests goes, if it's the site that's responding slowly (due to rate limiting, network conditions, etc.), you may consider caching (some) results of your external API requests (either for the life of the process or after some duration). That way queries for the same data won't require you to go over the network as much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.