Reading Files
Let's leverage the Node.js ecosystem to read files in our project
import fs from 'fs';
import path from 'path';
import { Species } from '../types';
export const getSpecies = (id: number): Promise<Species> => {
return new Promise((resolve, reject) => {
// let's wrap this in a try/catch block, because we may be asked to read a
// file that isn't there! But we can cleanly handle that, by letting the
// caller know that there was an error reading the file in our catch statement.
try {
// __dirname is a module constant that gets the current directory of
// our code. We need to go up two directories to get to the root,
// and then down the path of `/data/species/{id}.json`. This `path`
// package is the kosher way to create paths. It can look a bit
// much, but it's a safe way to access files and has a ton of superpowers.
// more info is here: https://nodejs.org/api/path.html
const filePath = path.join(__dirname, '..', '..', 'data', 'species', `${id}.json`);
// here, we're reading the file at that path. This may fail! If the user
// puts in a crazy random number or a string, or whatever, this will throw
// an error. You'll want to do some validation, and we'll get to that,
// so just know that calling this unprotected by validation isn't super safe
// but since we're the only ones using our code, we can trust that it will
// be okay for now.
const data = fs.readFileSync(filePath);
// let's console.log the data to see what we've got!
console.log(data);
resolve({} as Species)
} catch (e) {
reject("Pokemon not found")
}
})
}Last updated