Php Read and Write File Line by Line
How to read and write JSON file using Node.js ?
Node.js is an open source and cross-platform runtime environment for executing JavaScript code outside of the browser. Information technology is widely used in developing APIs and microservices from small to large companies.
JSON or JavaScript Object Notation is a light weight, text-based information interchange format. Like XML, it is one of the way of exchanging information between applications. This format of information is widely used by spider web applications/APIs to communicate with each other.
Reading a JSON file:
- Method i: Using require method: The simplest method to read a JSON file is to require information technology in a node.js file using
require()method.Syntax:
const data = require('path/to/file/filename');Example: Create a users.json file in the same directory where alphabetize.js file present. Add together following data to the json file.
users.json file:
[{"name":"John","age": 21,"language": ["JavaScript","PHP","Python"]},{"name":"Smith","age": 25,"linguistic communication": ["PHP","Go","JavaScript"]}]At present, add together the following code to your
index.jsfile.index.js file:
const users = require("./users");console.log(users);Now, run the file using the control:
node index.js
Output:
- Method two: Using the fs module: We tin besides use node.js fs module to read a file. The
fsmodule returns a file content in string format and so we need to convert it into JSON format past using JSON.parse() in-built method.
Add the following code into yourindex.jsfile:
index.js file:const fs = crave("fs");fs.readFile("users.json",function(err, data) {if(err)throwerr;const users = JSON.parse(data);console.log(users);});Now run the file again and you'll encounter an output like this:
Output:
Writing to a JSON file: We can write information into a JSON file by using the node.js fs module. We tin can use writeFile method to write data into a file.
Syntax:
fs.writeFile("filename", data, callback); Example: We will add together a new user to the existing JSON file, we have created in the previous example. This task will be completed in three steps:
- Read the file using one of the above methods.
- Add the data using
.push()method. - Write the new data to the file using
JSON.stringify()method to convert data into string.
const fs = require( "fs" );
const users = require( "./users" );
allow user = {
proper noun: "New User" ,
age: 30,
language: [ "PHP" , "Go" , "JavaScript" ]
};
users.button(user);
fs.writeFile( "users.json" , JSON.stringify(users), err => {
if (err) throw err;
console.log( "Washed writing" );
});
Run the file again and y'all will run into a message into the console:
At present check your users.json file it will looks something similar below:
Source: https://www.geeksforgeeks.org/how-to-read-and-write-json-file-using-node-js/
0 Response to "Php Read and Write File Line by Line"
Post a Comment