Intro
So we installed NodeJS on our machine.
Now we want to learn how to read a JSON file from our machine using the File System (FS) module.
Create a file with some data
- Open your terminal
- Create a file named
data-read.json
:
touch data-read.json
- Add some JSON data into it:
[{ "id": 1, "name": "miku86" }]
Write a simple script
- Open your terminal
- Create a file named
index.js
:
touch index.js
- Add this JavaScript code into it:
const fs = require("fs");
const FILE_NAME = "data-read.json";
const readFileAsync = () => {
fs.readFile(FILE_NAME, (error, data) => {
console.log("Async Read: starting...");
if (error) {
console.log("Async Read: NOT successful!");
console.log(error);
} else {
try {
const dataJson = JSON.parse(data);
console.log("Async Read: successful!");
console.log(dataJson);
} catch (error) {
console.log(error);
}
}
});
};
readFileAsync();
Note: We are using the async readFile
function to read data, because we don't want to block other tasks. You can also read data synchronous using readFileSync
, but this could block some other tasks.
Note: You can do a lot of stuff with the File System module, therefore read the docs of the FS module.
Every line explained
// import the file system module
const fs = require("fs");
// save the file name of our data in a variable (increase readability)
const FILE_NAME = "data-read.json";
const readFileAsync = () => {
// run async function to read file
fs.readFile(FILE_NAME, (error, data) => {
console.log("Async Read: starting...");
if (error) {
// if there is an error, print it
console.log("Async Read: NOT successful!");
console.log(error);
} else {
try {
// try to parse the JSON data
const dataJson = JSON.parse(data);
console.log("Async Read: successful!");
console.log(dataJson);
} catch (error) {
// else print an error (e.g. JSON was invalid)
console.log(error);
}
}
});
};
// run the function
readFileAsync();
Run it from the terminal
- Run it:
node index.js
- Result:
Async Read: starting...
Async Read: successful!
[ { id: 1, name: 'miku86' } ]
Further Reading
Questions
- Did you ever use the
fs Promises API
, that uses Promises instead of Callbacks?