skip to Main Content

I’m trying to create a json file using my website (that I will later deploy). This is the code I’m using

saveFile = (i, data) => {
  var filename = `${i}_may.json`;
  var folder_list = ["desktop", "data", filename];
  var dir = ".";
  folder_list.forEach(function (x, i) {
    dir = require("path").join(dir, `${x}`);
    if (!fs.existsSync(dir)) {
      fs.writeFileSync(dir, JSON.stringify(data));
    }
  });
};

But I keep getting this error

Error: ENOENT: no such file or directory, open 'desktopdata'


  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: 'desktop\data'

Of course the folder exists in my desktop. Is there a way to make it works but in local and after the deployment?

2

Answers


  1. To save a file to [current_dir]desktopdata, you can use the following code:

    saveFile = (i, data) => {
      const filename = `${i}_may.json`;
      const dir = require("path").join("desktop", "data", filename);
      console.log(dir);
    
      if (!fs.existsSync(dir)) {
        fs.writeFileSync(dir, JSON.stringify(data));
      }
    };
    

    Notice that the correct way to declare the path is to use require("path").join('desktop','data',filename), which ensures that the path is properly constructed regardless of the platform you are running on.

    Login or Signup to reply.
  2. I dont see why you are using forEach if you ultimately want to execute the writing only once.

    Also, using an absolute path is a better choice here. Regardless of your working dir, the script will always save the file in the correction location.

    const path = require('path');
    const fs = require('fs');
    
    saveFile = (i, data) => {
      var filename = `${i}_may.json`;
      var dir = path.join(process.env.HOME, "Desktop", "data", filename);
      fs.writeFileSync(dir, JSON.stringify(data));
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search