Home > Net >  write a json file in nodejs
write a json file in nodejs

Time:10-28

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

CodePudding user response:

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
}
  • Related