Path error when trying to write file to my repo

Hi !

I have a nuxt 3 app deployed on netlify. I’m trying to write a file to my github repo using this function:
(Here’s the function in server/api/produtcs)

import fs from "fs";
import { resolve } from "path";
import path from "path";
import simpleGit from "simple-git";
const git = simpleGit();

export default defineEventHandler(async (event) => {
  if (event.node.req.method === "POST") {
    const { fileName, content } = await readBody(event);
    const rootDir = process.cwd();
    const filePath = resolve(rootDir, `./content/products/${fileName}.md`);

    try {
      await fs.promises.writeFile(filePath, content);
      try {
        await git.cwd(rootDir);
        await git.add(".");
        await git.commit(`Added new file: ${filePath}`);
        await git.push();
        console.log(`Commited and pushed changes to repository`);
      } catch (err) {
        console.log("commit error", err);
        return {err};
      return "success";
    } catch (err) {
      console.log("file error", err);
      return {err};
  } else {
    return 'error';

But I’m getting this error:

  1. code: “ENOENT”
  2. errno: -2
  3. path: “/var/task/content/products/”
  4. syscall: “open”

Thanks in advance for your help!

Hi :wave:t6: ,this looks like (just a guess without your repo) that your file name might not exist. Can you ensure that the file exists at the specified path. Also check the file path location and permissions.

I’m trying to write a file named “” in the /content/products directory.
The problem is that I can’t access the directory.

Any idea how I can access the root dir of my repo ?

@nezlicodes Are you sure that the /content/products directory already exists?

The fs implementation of writeFile only concerns itself with writing the file, it won’t create the directories that you’ve specified in the path if they don’t yet exist.

There’s lots of ways you can solve for this, a few are…

  • Ensure that the directory actually exists in your repository
    If it’s an empty directory it won’t be going into the repository and you can use a .gitkeep file

  • Use fs.mkdir to make the directory before attempting to write into it

  • Use the fs-extra package instead of fs
    Then you can use .outputFile