Answer the question
In order to leave comments, you need to log in
How to close an open file in node js?
Hello. There is a script that writes data to a json file. The first time everything works as it should, but if you do the same operation again, the page is not found and Technical information: connectionfailure. Nothing is output to the console. Here's the problematic function:
async save() {
const courses = await Course.getAll()
courses.push(this.toJSON())
return new Promise(function(resolve, reject) {
fs.writeFile(
path.join(__dirname, '..', 'data', 'courses.json'),
JSON.stringify(courses),
function (err){
if(err) {
reject(err)
} else {
resolve(true)
}
}
)
})
}
static getAll() {
return new Promise(function(resolve, reject) {
fs.readFile(
path.join(__dirname, '..', 'data', 'courses.json'),
'utf-8',
function (err, content) {
if (err){
reject(err)
} else {
resolve(JSON.parse(content))
}
}
)
})
}
const {Router} = require('express')
const Course = require('../models/course')
const router = Router()
router.get('/', function (req, res) {
res.render('add', {
title: 'Добавить курс',
isAdd: true
})
})
router.post('/', async function (req, res) {
const course = new Course(req.body.title, req.body.price, req.body.img)
await course.save()
res.redirect('/courses')
})
module.exports = router
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question