I
I
Ivan Ivanov2020-03-01 11:52:10
Node.js
Ivan Ivanov, 2020-03-01 11:52:10

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)
                    }
                }
            )
        })
    }

If you comment it out, then no errors occur. It seems to me that since it doesn’t work after the first execution, it means that the file remains open and this prevents
the getAll () method from overwriting the file again:
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))
                    }

                }
            )
        })
    }

By the way, writing to the file is carried out, just the page is not available. Router:
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 question

Ask a Question

731 491 924 answers to any question