“This is the 23rd day of my participation in the First Challenge 2022. For details: First Challenge 2022”
Project source: gitee.com/yang-yiming…
In the last article, we were able to transfer our data to the back end. In this post we’re going to store the data. Instead of storing it in a database, we store it in a JSON file.
Train of thought
Create a DB folder on the server and create a new doing. json under it. Click Create task to read doing. json file, then write data to json file.
Read the file
Node reads files
Let’s refer to the node read file
The document address
const fs = require('fs')
fs.readFile('/Users/joe/test.txt'.'utf8' , (err, data) = > {
if (err) {
console.error(err)
return
}
console.log(data)
})
Copy the code
Let’s apply that to us
The import
// Read the file
const fs = require('fs');
// Find the current path
const path = require('path')
Copy the code
Let’s take a look at the path
router.post('/create'.function (req, res, next) {
console.log(__dirname)
res.send({
data: 'ok'
})
Copy the code
We want to find the DB directoryusepath.join()
Methods..
Go to the layer above the router.
router.post('/create'.function (req, res, next) {
console.log(__dirname)
const dbPath = path.join(__dirname,'.. ')
console.log(dbPath)
res.send({
data: 'ok'})})Copy the code
You can see that the path is now at the Server levelAdd the parameter ‘db’ to the join method, which is the db folder location
const dbPath = path.join(__dirname,'.. '.'db')
Copy the code
Test reading the file
Write anything in doing. jsonRemember to run the server again.
router.post('/create'.function (req, res, next) {
console.log(__dirname)
const dbPath = path.join(__dirname,'.. '.'db')
console.log(dbPath)
// '\\'
fs.readFile(`${dbPath}\/DOING.json`.'utf8'.(err, data) = > {
if (err) {
console.error(err)
return
}
console.log(data)
})
res.send({
data: 'ok'})})Copy the code
You can see that the read succeeded.
Combine our logic
Read the parameters passed by the front end
const newTask = req.body
Copy the code
Define json file path variables
const dbPath = path.join(__dirname, '.. '.'db')
const dbFile = `${dbPath}\/DOING.json`
Copy the code
Read the file before you write it
- Is a nested, read file function to call the write operation function.
- Returns if the read or write fails
data:[]
- Finally, if the file is successfully written, new JSON data is returned
📢 The new newData data needs to be treated with JSON.
router.post('/create'.function (req, res, next) {
// Create new task data
const newTask = req.body
const dbPath = path.join(__dirname, '.. '.'db')
const dbFile = `${dbPath}\/DOING.json`
// '\'
/** * read the file before writing the file */
fs.readFile(dbFile, 'utf8'.(err, data) = > {
// Return null data on failure
if (err) {
console.error(err)
res.send({
data: [].code: 0.msg: err
})
return
}
// Merge the new task data and read the data in the original file
const newData = JSON.stringify([newTask, ...data])
fs.writeFile(dbFile, newData, wrerr= > {
// Return null data on failure
if (wrerr) {
console.error(err)
res.send({
data: [].code: 0.msg: err
})
return
}
console.log(newData)
// The file was successfully written.
res.send({
data: newData,
code: 1.msg: ' '})})})})Copy the code
Problems encountered
When we insert two pieces of data it starts to look like this, broken up into characters.Later it was found that we had some formatting problems. Make the following improvements:
[{}, {}]Copy the code
The service side
Check if the data read is null. Null
let newData = null;
// Merge the new task data and read the data in the original file remember to do some JSON processing
if(data){
const oldData = JSON.parse(data)
The stringify() method converts a JavaScript object or value to a JSON string
newData = JSON.stringify([...oldData,newTask])
console.log(newData,'nnn')}else{
// Put it in []
newData = JSON.stringify([newTask])
}
Copy the code