在 nodejs 中写一个 json 文件

write a json file in nodejs

我有现有的 products.json 数据,其中包含一个数据数组,我想在 post 请求中推送一个新的 json 对象。虽然 json 对象数组得到更新,但是当我打开 product.json 文件时,我没有在该文件中看到新添加的数据。我收到这样的错误

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

文件夹结构

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

产品控制器文件

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

产品模型文件

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 文件

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

路径似乎不正确,这就是它没有更新文件的原因。


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

您可能需要等待文件操作执行:


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
}