0

enter image description hereI have existing products.json data which consists of an array of data, I wanted to push a new json object on a post request. While the array of json objects gets updated but when I open the product.json file I don't see the newly added data in that file. And I get an error like this

[Error: ENOENT: no such file or directory, open '../data/products.json'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '../data/products.json'
}

Folder Structure

 controllers
     productController.js
models
     productModels.js 
data
   products.js
node_modules
package.json
package-lock.json
server.js

product controller file

export const createProduct = async (req, res) => {
    try{
        const product = {
            userId: 'req.userId',
            id: 'req.id',
            title: 'req.title',
            body: 'req.body'
        }
        const newProduct = await create(product)
        res.writeHead(201, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(newProduct))
    }catch(err){
        console.log(err)
    }
}

product model file

export const create = (product) => {
    const id = uuid()
    const newProduct = {...product, id}
    products.push(newProduct)

    writeDataToFile('../data/products.json', products)

    const promise = new Promise((resolve, reject) => {
        const newProduct = products.find(element => element.id = id)
        setTimeout(() => {
            resolve(newProduct)
        }, 1000)
    })
    return promise
}

utils.js file

import { writeFile } from 'fs/promises';

export const writeDataToFile = async (filename, content) => {
    try {
        console.log(filename)
        console.log(process.cwd())
        await writeFile(filename, JSON.stringify(content));      
      } catch (err) {
        console.error(err);
      }
}

enter image description here

enter image description here

9
  • ` While the array of json objects gets updated but when I open the product.json file`,What does it mean? Are you reading the data from file first? Commented Oct 27, 2021 at 12:00
  • Have you checked this? stackoverflow.com/questions/43260643/… If it will not work in you then we find next solution for your question. Commented Oct 27, 2021 at 12:00
  • @DarshanRaval SO is asking a different question based on the scenario provided in the question. Commented Oct 27, 2021 at 12:01
  • 1
    @ApoorvaChikara Sorry for that. Commented Oct 27, 2021 at 12:02
  • 1
    @DarshanRaval Don't be sorry, it's ok. Commented Oct 27, 2021 at 12:10

1 Answer 1

1

It seems the path is incorrect and thats why it is not updating the file.


import { writeFile } from 'fs/promises';
import * as path from 'path';

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export const writeDataToFile = async (filename, content) => {
    try {
        console.log(filename)
        console.log(process.cwd());
        console.log(path.join(__dirname, filename)) // check if the path is correct
        await writeFile(path.join(__dirname, filename), JSON.stringify(content));      
     return 'File Updated';
      } catch (err) {
        console.error(err);
      }
}

You might need to await for the file operation to perform:


export const create = (product) => {
    const id = uuid()
    const newProduct = {...product, id}
    products.push(newProduct)

    await writeDataToFile('../data/products.json', products)

    const promise = new Promise((resolve, reject) => {
        const newProduct = products.find(element => element.id = id)
        setTimeout(() => {
            resolve(newProduct)
        }, 1000)
    })
    return promise
}
Sign up to request clarification or add additional context in comments.

12 Comments

It's not working, I get error, "ReferenceError: __dirname is not defined". I haven't made any mistake in importing the path module.
Yes, You are using es module system and it won't work with this directly. I have added the code check with this.
I can successfully write the file, the product.json file gets updated but now when I create a request the server sends a response "Error: Server returned nothing (no headers, no data)"
Great, I believe you can ask a new question for that. As this question(initially what you have asked) is resolved, the answer should be marked and upvote for future reference.
You are welcome 🤗 .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.