Как решить [Ошибка: ENOENT: нет такого файла или каталога, открыть] для writeFile () - PullRequest
0 голосов
/ 28 февраля 2019

эта функция должна создать файл, мой скрипт включает 20 из них в последовательности

const fs     = require('fs');

createFile( file.name + files.create_meta, blueprint.create_meta, data )

эта функция создает контент

function createFile(filePath, blueprintPath, data) {
   const blueprint = fs.readFileSync(blueprintPath, 'utf8');
   const content = template(blueprint, {
     email: data.email,
     name: data.name,
     date: data.date,
   })

  fs.writeFile(filePath, content, function (err) {
    console.log(err);
  })
}

иногда это работает, но часто я получаюэто сообщение об ошибке:

 [Error: ENOENT: no such file or directory, open ] 

Если это сообщение появляется, файл не был создан, поскольку файлы не существуют в начале, а ошибка означает, что функция не может найти файл по этому пути.

как я могу гарантировать, что моя функция создает файлы?

1 Ответ

0 голосов
/ 28 февраля 2019

Вы можете обновить функцию createFile следующим образом.

const fs = require("fs");

function createFile(filePath, blueprintPath, data) {
  if (!fs.existsSync(blueprintPath)) {
    throw new Error(blueprintPath + " does not exist");
  }
  const blueprint = fs.readFileSync(blueprintPath, "utf8");
  const content = template(blueprint, {
    email: data.email,
    name: data.name,
    date: data.date
  });

  // creates an empty file if doesn't exist
  fs.closeSync(fs.openSync(filePath, "w"));
  fs.writeFile(filePath, content, function(err) {
    console.log(err.message);
  });
}

try {
  // call your function in try-catch
  createFile("./test.txt", "testtest", "test");
} catch (error) {
  console.log(error.message);
}




...