How to Read in Each Line of a Json File Javascript
How to Read and Write JSON with NodeJS
In this tutorial nosotros will go over how read and write a JSON file with NodeJS. Information technology should come at no surprise that Node makes working with JSON extremely like shooting fish in a barrel, and with the built in fs
module, reading and writing to the file system is equally easy.
This tutorial is written in two parts, the first volition embrace reading from a JSON file, the 2nd part will cover writing to a JSON file.
Reading a file TLDR: To read a file you lot can either employreadFile
which will read a file asynchronously, and you need to laissez passer a file path, options and a callback, or you can utilisereadFileSync
, which will read the file synchronously, and you just pass in a file path and options, this function will render the files data.
Writing a file TLDR: To write to a file you can either applywriteFile
which will write a file asynchronously, and y'all need to laissez passer in a file path, the data you want to write, your options and a callback to handle errors. Or, you tin can usewriteFileSync
, which will write the file synchronously, and yous need to pass a file path, the data you want to write and your options.
Alphabetize
- Reading a file with readFile
- Reading a file with readFileSync
- Writing a file with writeFile
- Writing a file with writeFileSync
Earlier we get started, this is the data that I am working with, and I have this in a file chosen testJsonFile.json
which is in my root directory:
{ "frameworks": [ "express", "feathers js", "meteor", "koa" ] }
At present that we have the information setup, let's look at the start two lines of my index.js
file:
const fs = crave('fs') allow parsedJsonData
On the first line, we crave the fs
module. We volition need this to read and write to the file organization and we will use this throughout the tutorial.
On the adjacent line we setup a variable that we will utilize afterward to shop the JSON data that has been read from the file system, nosotros volition then add an additional JavaScript framework to that data and and so write it back to the file organization.
Reading a JSON file
The fs
module provides a couple of popular ways to read a file, namely these are, readFile
and readFileSync
. We will utilize both of these functions, depending on your situation, reading a file synchronously might non exist an consequence at all, it also makes it a bit easier in my opinion as we don't need to deal with callbacks.
Reading a file with readFile
I am going to start with the code, and and then I will explain information technology afterwards:
// 1 fs.readFile('./testJsonFile.json', 'utf8', (fault, data) => { // 2 if (error) { console.log(`ERROR: ${error}`) return } // 3 const jsonData = JSON.parse(data) // iv parsedJsonData = jsonData // five // Check the keys that jsonData has console.log(Object.keys(jsonData)) // half dozen jsonData.frameworks.forEach(framework => { console.log(`Framework: ${framework}`) }) })
Ok, permit's run through what is happening in the above code snippet:
- This is the call to the
readFile
role. It takes a few arguments, the first being the path to the file you want to read, the second being theoptions
yous want to pass in, we are passing inutf-viii
for the encoding, and then the last argument is a callback. - The first function of the callback, we are just making sure that an
fault
does not exist, if it does, we will write the error to the console, and return. Using areturn
here is a personal preference. If I can stay away from usingelse
then I by and large will, but, yous could apply anif else
instead and take the rest of the code be in theelse
block. - Here we parse the
data
which is the 2d argument for the callback, and we assign the parsed data to thejsonData
abiding. - Nosotros can now assign the parsed JSON data to the global variable that we created at the start of the tutorial, we will use this later when writing to the file system.
- This isn't an important line, only we are just press out all the
keys
of thejsonData
object. For the sake of this tutorial, this makes information technology easier to see thekeys
that the exam data has. - Lastly, we loop through the
frameworks
and print information technology to the console.
And that is it! That is how elementary information technology is to read a json file asynchronously using Node.
Reading a file with readFileSync
In one case again, let's start with the code:
// 1 endeavor { // 2 const data = fs.readFileSync('./testJsonFile.json', 'utf8') // 3 const jsonData = JSON.parse(data) // iv parsedJsonData = jsonData // 5 // Check the keys that jsonData has console.log(Object.keys(jsonData)) // 6 jsonData.frameworks.forEach(framework => { panel.log(`Framework: ${framework}`) }) } catch (fault) { // 7 console.log(`ERROR: ${fault}`) }
Most of the steps are quite like to the asynchronous example, the large deviation is the effort grab
.
- We need use a
try take hold of
consideringreadFileSync
tin can throw an mistake. In the asynchronous instance, this error would be passed as an statement to the callback, simply the synchronous version does non use a callback, then the role itself will throw an error and we need to handle that. - We use the
readFileSync
function to read the file. The first argument is the file path and the second argument is for options. Again, for the second argument, we pass through the encoding that nosotros want to use. ThereadFileSync
function returns the information immediately. which is why we assign it to a abiding. - At present, we can parse the
data
as we have earlier past usingJSON.parse
. - We assign the parsed information to our
parsedJsonData
global variable and so that nosotros tin can apply the data afterward on. - Print out the
keys
of the JSON object, which helps for debugging, and just makes things a bit clearer in a tutorial. - Nosotros loop through all the values for the
frameworks
key, and print those values to the console. - As mentioned before, we need a
try catch
because of the modereadFileSync
works, and this is where we catch the error and print it to the panel.
As I have mentioned earlier, this is my preferred way to read files because it is and then straight forwards, simply, making use of the readFileSync
role heavily depends on what your use case is.
Writing a JSON file
In the previous section we spoke about reading a file using the fs
module. Writing to the file arrangement also uses the fs
module, and it too has two functions that we volition utilise. Namely, writeFile
and writeFileSync
. This works in a similar way to the read functions.
Writing a file with writeFile
Let'due south get-go with the code:
// 1 parsedJsonData.frameworks.push('nest js') // two const asyncFrameworksData = JSON.stringify(parsedJsonData) // iii fs.writeFile('./testJsonFile.json', asyncFrameworksData, 'utf-8', (error) => { // 4 if (fault) { panel.log(`WRITE ERROR: ${error}`) } else { // 5 console.log('FILE WRITTEN TO') } })
- Nosotros are now going to brand utilise of the
parsedJsonData
that nosotros created at the offset of the tutorial. SinceparsedJsonData
already contains a JSON object, we can push an boosted element,next js
, onto theframeworks
holding. - Before nosotros write to the file, we demand to stringify the JSON object.
- Now that we have updated and stringified
parsedJsonData
, we can writeasyncFrameworksData
to our file. To write to a file we use thewriteFile
part from thefs
module. The first argument is the file path, the second argument is the information we want to write, in our caseasyncFrameworksData
, the third argument is foroptions
, once again we are going to apply it to set our encoding toutf-8
. Lastly, we need to pass in a callback. This callback simply takes one statement, and that is for an fault. - We check if an error exists, if it does we will print it in the console.
- If there is no error, we print to the console that the file has been written to.
That is all that is needed to write to a file asynchronously, merely as easy, if not easier than reading a file.
Writing a file with writeFileSync
Starting with the code one again:
// 1 parsedJsonData.frameworks.push('nest js') // two try { // 3 const frameworksData = JSON.stringify(parsedJsonData) // iv fs.writeFileSync('./testJsonFile.json', frameworksData, 'utf-8') } catch (error) { // 5 panel.log(`WRITE Mistake: ${error}`) }
- If you have read the
writeFile
department, we are doing the same affair, nosotros only add a new element to the frameworks array in theparsedJsonData
object. - Because at that place is no callback provided to the
writeFileSync
part, information technology will throw an mistake if there is an issue, so we need to wrap it in atry catch
cake. - Same as the previous section. Before we write the data, we need to stringify it.
- Nosotros write the data to the specified file path. Similarly to
writeFile
,writeFileSync
takes the file path as the starting time argument, the data we want to write,frameworksData
, as the second argument and lastly information technology takes an options argument, which we use to pass the encoding that we want, which isutf-8
. - This follows on from point 2, in the catch part of the
try catch
we grab any errors and then nosotros will print those to our console.
The original data in the testJsonFile.json
looked like this:
{ "frameworks": [ "express", "feathers js", "meteor", "koa" ] }
After we write to it, it should expect like this:
{ "frameworks": [ "express", "feathers js", "falling star", "koa", "nest js" ] }
Conclusion
This tutorial was quite long, but the code itself is quite easy. Reading from a file and writing to a file synchronously is easier than asynchronously, simple because yous do need the callback, and everything works as expected.
If you need to read the file asynchronously and so write to it afterwards, remember that you need to handle the writing from inside callback, otherwise you could read a file, and while you are reading the file, the write could have already happened.
You lot tin find all the source code here.
Source: https://programmingwithswift.com/how-to-read-and-write-json-with-nodejs/
0 Response to "How to Read in Each Line of a Json File Javascript"
Post a Comment