How to use the promises function from fs

Find comprehensive JavaScript fs.promises code examples handpicked from public code repositorys.

fs.promises is a module in the Node.js file system (fs) module that provides an alternative set of methods for working with files and directories that return promises instead of using callbacks.

388
389
390
391
392
393
394
395
396
      res,
      filename,
      ...type,
      data,
      deleteFile() {
         return filename && fs.promises.unlink(filename)
      }
   }
}
fork icon332
star icon109
watch icon0

+ 3 other calls in file

141
142
143
144
145
146
147
148
149
150
if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
let type = await FileType.fromBuffer(data) || {
    mime: 'application/octet-stream',
    ext: '.bin'
}
if (data && returnAsFilename && !filename) (filename = path.join(__dirname, '../tmp/' + new Date * 1 + '.' + type.ext), await fs.promises.writeFile(filename, data))
return {
    res,
    filename,
    ...type,
fork icon320
star icon87
watch icon1

+ 3 other calls in file

How does fs.promises work?

The fs.promises module is a part of the Node.js file system (fs) module, which allows you to work with files and directories in a Node.js application. When you require the fs module in your Node.js application, you can access the fs.promises module as a property of the main fs module. The fs.promises module provides an alternative set of methods for working with files and directories that return promises instead of using callbacks. For example, instead of using the fs.readFile method that takes a callback, you can use the fs.promises.readFile method that returns a promise. You can then use the then method of the promise to handle the result of the operation, or the catch method to handle any errors. The fs.promises module also provides methods for other file system operations such as writeFile, mkdir, rmdir, rename, and more. All of these methods return promises, making it easier to write asynchronous code without using callbacks. When you are finished using the fs.promises module, you can simply call require('fs') again to access the original fs module with the callback-based methods. Overall, the fs.promises module provides a convenient way to work with files and directories in a Node.js application using promises instead of callbacks.

402
403
404
405
406
407
408
409
410
411
  for await (const zipEntry of zip) {
    const name = zipEntry.path;
    const contents = (await zipEntry.buffer()).toString('base64');
    submission.submitted_answer['_files'].push({ name, contents });
  }
  await fs.promises.unlink(zipPath);
},
(callback) => {
  questionServers.getModule(question.type, (err, ret_questionModule) => {
    if (ERR(err, callback)) return;
fork icon251
star icon248
watch icon14

239
240
241
242
243
244
245
246
247
248
  pathFile = await writeExif(media, {
    packname: options.packname ? options.packname : global.packname,
    author: options.author ? options.author : global.author,
    categories: options.categories ? options.categories : [],
  });
  await fs.promises.unlink(filename);
  type = "sticker";
  mimetype = "image/webp";
} else if (/image/.test(mime)) type = "image";
else if (/video/.test(mime)) type = "video";
fork icon27
star icon8
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const fs = require("fs").promises;

// Read a file using promises
fs.readFile("myfile.txt", "utf8")
  .then(function (data) {
    console.log("File contents:", data);
  })
  .catch(function (err) {
    console.log("Error reading file:", err);
  });

// Write a file using promises
fs.writeFile("myfile.txt", "Hello, world!", "utf8")
  .then(function () {
    console.log("File written successfully");
  })
  .catch(function (err) {
    console.log("Error writing file:", err);
  });

In this example, we first require the fs module and access the fs.promises module as a property of the fs module. We then use the fs.promises.readFile method to read the contents of a file named myfile.txt, passing in the file encoding as the second argument. The then method of the resulting promise is used to handle the file contents, and the catch method is used to handle any errors that occur. We then use the fs.promises.writeFile method to write the string "Hello, world!" to the same file, again passing in the file encoding as the third argument. The then method of the resulting promise is used to log a success message, and the catch method is used to handle any errors that occur. Overall, using fs.promises allows us to read and write files using promises instead of callbacks, making the code easier to read and write.

72
73
74
75
76
77
78
79
80
81
  }
} catch (error) {
  console.error('Fail to read File', path + '.json', error.message)
}
async function writeAsync () {
  fs.promises.writeFile(path + '.json', JSON.stringify(data)).then(() => {}).catch((error) => {
    console.error('Fail to write File', path + '.json', error.message)
  })
}
var handler = {
fork icon0
star icon3
watch icon2

+ 27 other calls in file

51
52
53
54
55
56
57
58
59
60
build.onLoad({ filter: /\.imba1/ }, async (args) => {
	// console.log('loading imba',args);
	if (watcher) watcher.add(args.path);

	let key = `${args.path}:${options.platform}`
	let raw = await fs.promises.readFile(args.path, 'utf8');
	let cached = compileCache[key];

	if (cached && cached.input == raw) {
		return { contents: cached.output };
fork icon185
star icon0
watch icon104

934
935
936
937
938
939
940
941
942
943
944
945
  console.log('done');
};


const loadMetadatadict = async () => {
  if (!fs.existsSync('./temp') && !fs.existsSync('./temp/metadatadict.json')) {
    return fs.promises.readFile('./temp/metadatadict.json', 'utf8').then((data) => JSON.parse(data));
  }


  return {};
};
fork icon99
star icon159
watch icon9

1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
    console.log(inspect(out));
    return out;
}


function create_file(file_path) {
    return fs.promises.appendFile(file_path, file_path + '\n');
}


async function create_object(object_path, data, version_id) {
    const target_file = await nb_native().fs.open(DEFAULT_FS_CONFIG, object_path, 'w+');
fork icon68
star icon226
watch icon17

+ 17 other calls in file

12
13
14
15
16
17
18
19
20
21
22
    throw new Error(`No such file: ${source}`)
  }
  if (!existsDir(target)) {
    throw new Error(`Target is a directory: ${target}`)
  }
  await fs.promises.cp(source, target, { force: true, recursive: false });
}


/**
 * @param {number} millis 
fork icon3
star icon14
watch icon5

+ 9 other calls in file

474
475
476
477
478
479
480
481
482
483
   else if (/image/.test(mime)) type = 'image'
   else if (/video/.test(mime)) type = 'video'
   else if (/audio/.test(mime)) type = 'audio'
   else type = 'document'
   await client.sendMessage(jid, { [type]: { url: pathFile }, caption, mimetype, fileName, ...options }, { quoted, ...options })
   return fs.promises.unlink(pathFile)
   }

/**
 * 
fork icon2
star icon2
watch icon0

+ 5 other calls in file

13
14
15
16
17
18
19
20
21
22
23
24


async function generateHtml(filepath, modelConfig, config) {
    const favicon = modelConfig.favicon || config.favicon;
    const viewport = modelConfig.viewport || config.viewport;
    const title = modelConfig.name || config.name;
    let html = await fs.promises.readFile(path.join(htmlDir, filepath), 'utf8');


    if (title) {
        html = html.replace(
            /<title>.*?<\/title>/,
fork icon1
star icon5
watch icon3

554
555
556
557
558
559
560
561
562
    res,
    filename,
    ...type,
    data,
    deleteFile() {
      return filename && fs.promises.unlink(filename);
    },
  };
};
fork icon0
star icon4
watch icon0

+ 9 other calls in file

508
509
510
511
512
513
514
515
516
517
else if (/image/.test(mime)) type = 'image'
else if (/video/.test(mime)) type = 'video'
else if (/audio/.test(mime)) type = 'audio'
else type = 'document'
await haikal.sendMessage(jid, { [type]: { url: pathFile }, caption, mimetype, fileName, ...options }, { quoted, ...options })
return fs.promises.unlink(pathFile)}
//=================================================//
/**
 * 
 * @param {*} jid 
fork icon1
star icon1
watch icon0

+ 4 other calls in file

12
13
14
15
16
17
18
19
20
21
22
23
  fs.writeFileSync(filename, fileBuffer)
}


;(async () => {
  try {
    const files = await fs.promises.opendir('./public/bars')
    let filesStripped = 0


    for await (const file of files) {
      if (file.name.includes('.jpg')) {
fork icon1
star icon4
watch icon0

191
192
193
194
195
196
197
198
199
200
  );
}
async downloadMediaMessage() {
  let buff = await this.m.download();
  let type = await fileType.fromBuffer(buff);
  await fs.promises.writeFile(new Date() + type.ext, buff);
  return new Date() + type.ext;
}
async reply(text, opt = {}) {
  return this.client.sendMessage(
fork icon6
star icon1
watch icon1

+ 2 other calls in file

482
483
484
485
486
487
488
489
490
491
if (!isRoot) {
  res.redirect("/admin/backup");
  return;
}
const auto_backup_directory = getState().getConfig("auto_backup_directory");
const fileNms = await fs.promises.readdir(auto_backup_directory);
const backupFiles = fileNms.filter(
  (fnm) => fnm.startsWith("sc-backup") && fnm.endsWith(".zip")
);
send_admin_page({
fork icon194
star icon0
watch icon31

764
765
766
767
768
769
770
771
772
773
774
775


}


app.post("/getcharacters", jsonParser, async function(request, response) {
  try {
    const files = await fs.promises.readdir(charactersPath);
    const imgFiles = files.filter(file => file.endsWith(`.${characterFormat}`));
    const characters = {};
    let i = 0;

fork icon60
star icon276
watch icon17

494
495
496
497
498
499
500
501
502
503
result = result.replace(/#columns_name/g, JSON.stringify(columnNames));
result = result.replace(/#report_duration/g, report_data_json.duration);

// Verify that the default folder for report exists
if (!fs.existsSync(`.${SPLIT_PATH}report${SPLIT_PATH}${testUuid}${SPLIT_PATH}${virtualUser}${SPLIT_PATH}`)) {
  await fs.promises.mkdir(
    `.${SPLIT_PATH}report${SPLIT_PATH}${testUuid}${SPLIT_PATH}${virtualUser}${SPLIT_PATH}`,
    { recursive: true }
  );
}
fork icon0
star icon1
watch icon1

+ 11 other calls in file

77
78
79
80
81
82
83
84
85
86
        headers: this.headers,
    });
}

async arrayBuffer() {
    const data = await fs.promises.readFile(this.filePath);
    return data.buffer;
}

async blob() {
fork icon38
star icon0
watch icon16

+ 2 other calls in file