How to use the promisify function from util

Find comprehensive JavaScript util.promisify code examples handpicked from public code repositorys.

util.promisify is a function in Node.js that converts a callback-based asynchronous function into a Promise-based function, making it easier to handle asynchronous operations in JavaScript.

10
11
12
13
14
15
16
17
18
19
20
const util = require('util')
const createError = require('@fastify/error')
const sendToWormhole = require('stream-wormhole')
const deepmergeAll = require('@fastify/deepmerge')({ all: true })
const { PassThrough, pipeline, Readable } = require('stream')
const pump = util.promisify(pipeline)
const secureJSON = require('secure-json-parse')


const kMultipart = Symbol('multipart')
const kMultipartHandler = Symbol('multipartHandler')
fork icon81
star icon312
watch icon21

33
34
35
36
37
38
39
40
41
42
43
44
45


const fluxDirPath = path.join(__dirname, '../../../');
const appsFolder = `${fluxDirPath}ZelApps/`;


const cmdAsync = util.promisify(nodecmd.get);
const crontabLoad = util.promisify(systemcrontab.load);
const dockerPullStreamPromise = util.promisify(dockerService.dockerPullStream);
const dockerStatsStreamPromise = util.promisify(dockerService.dockerContainerStatsStream);


const scannedHeightCollection = config.database.daemon.collections.scannedHeight;
fork icon227
star icon164
watch icon24

+ 14 other calls in file

How does util.promisify work?

When you call util.promisify with a function that follows the Node.js callback pattern (i.e., a function that takes a callback as its last argument), it returns a new function that returns a Promise. This new function has the same signature as the original function, but instead of taking a callback, it returns a Promise that resolves with the same value that would have been passed to the callback. Under the hood, util.promisify creates a new function that returns a Promise and sets up a callback function to be called when the original function completes. The callback function then resolves or rejects the Promise, depending on whether the original function completed successfully or encountered an error. When you call the new Promise-based function returned by util.promisify, it executes the original function and waits for it to complete. If the original function returns an error, the Promise is rejected with that error. Otherwise, the Promise is resolved with the value returned by the original function. Overall, util.promisify simplifies working with asynchronous functions in JavaScript by allowing you to use Promises instead of callbacks, making it easier to write asynchronous code that is more readable and maintainable.

32
33
34
35
36
37
38
39
40
41
42
const minimist = require('minimist');
const { compileBuildTask } = require('./gulpfile.compile');
const { compileExtensionsBuildTask, compileExtensionMediaBuildTask } = require('./gulpfile.extensions');
const { getSettingsSearchBuildId, shouldSetupSettingsSearch } = require('./azure-pipelines/upload-configuration');
const { promisify } = require('util');
const glob = promisify(require('glob'));
const rcedit = promisify(require('rcedit'));


// Build
const vscodeEntryPoints = [
fork icon22
star icon17
watch icon13

+ 3 other calls in file

3
4
5
6
7
8
9
10
11
12
13
14
15
const path = require('path');
const expect = require('expect.js');
const fs = require('fs/promises');
const util = require('util');


const glob = util.promisify(require('glob'));


const Porter = require('../..');


describe('Packet', function() {
fork icon7
star icon40
watch icon9

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const fs = require("fs");
const util = require("util");

// Create a Promise-based version of fs.readFile
const readFile = util.promisify(fs.readFile);

// Use the Promise-based version of fs.readFile
readFile("file.txt", "utf8")
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, we're using util.promisify to create a Promise-based version of Node.js's fs.readFile function, which reads a file from disk. We then use the new Promise-based readFile function to read a file named file.txt and log its contents to the console. Note that we're using then and catch to handle the Promise returned by readFile, which allows us to handle both successful and failed file reads in a more readable way than using callbacks.

128
129
130
131
132
133
134
135
136
137
resolver: new dns.Resolver(),
resolve4: null,
// Determines if we need to use a fallback DNS server or if our assigned DNS service works properly
setResolver: async () => {
  if (!this.dns.resolve4) {
    this.dns.resolve4 = promisify(this.dns.resolver.resolve4).bind(this.dns.resolver)
  }
  let resolved
  try {
    if (!isFQDN(KUBESAIL_AGENT_GATEWAY_TARGET)) {
fork icon7
star icon26
watch icon4

+ 5 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26
const Bumpr = require('../bumpr')
const {Logger} = require('../logger')
const {createReadStream, exec, existsSync, readdir, statSync, writeFile} = require('../node-wrappers')
const utils = require('../utils')


const realExec = util.promisify(cp.exec)


function getVersionCmd(filename) {
  return `node -e "console.log(require('./${filename}').version)"`
}
fork icon3
star icon3
watch icon0

912
913
914
915
916
917
918
919
920
921
"use strict";
var { constants: BufferConstants } = require("buffer");
var stream = require("stream");
var { promisify } = require("util");
var bufferStream = require_buffer_stream();
var streamPipelinePromisified = promisify(stream.pipeline);
var MaxBufferError = class extends Error {
  constructor() {
    super("maxBuffer exceeded");
    this.name = "MaxBufferError";
fork icon1
star icon6
watch icon4

17
18
19
20
21
22
23
24
25
26
27
28
    set_get_started();
});


//INIT DB
let db = new sqlite3.Database('users.db');
const queryDB = promisify(db.all).bind(db);


let users = {};
const MAJEURS = { "CBD": "CONCEP.LOGICIELLE/BIG DATA",
    "ROSE": "ROBOTIQUE",
fork icon0
star icon4
watch icon1

108
109
110
111
112
113
114
115
116
117
    next,
  );
}

// 2) Verify token
const decode = await promisify(jwt.verify)(token, process.env.JWT_SECRET);

// 3) check if the user is exist (not deleted)
const user = await User.findById(decode.id);
if (!user) {
fork icon0
star icon2
watch icon0

93
94
95
96
97
98
99
100
101
102
103
104
//       new AppError('You are not logged in! Please log in to get access.', 401)
//     );
//   }


//   // 2) Verification token
//   const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);


//   // 3) Check if user still exists
//   const currentUser = await User.findById(decoded.id);
//   if (!currentUser) {
fork icon0
star icon1
watch icon1

95
96
97
98
99
100
101
102
103
104
    new AppError("you are not logged-in, please login to get access", 401)
  );
}

// token verification
const decoded = await promisify(jwt.verify)(token, process.env.SECRET_STRING); // make jwt.verify returns a promise

//check if the user still exists
const user = await prisma.user.findUnique({
  where: {
fork icon0
star icon1
watch icon1

18
19
20
21
22
23
24
25
26
27
28
29
//     post: 6379,
//     password: redisPassword
// };


// const client = redis.createClient(newClient);
// const setAsync = promisify(client.set).bind(client);
// const getAsync = promisify(client.get).bind(client);


const DB = require('../helpers/DB');
const connection = DB.getConnection();
fork icon0
star icon1
watch icon1

79
80
81
82
83
84
85
86
87
88

if (!token) {
	return next(new AppError('you are not logged in', 401))
}

const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);

const currentUser = await User.findById(decoded.id);

if (!currentUser) {
fork icon1
star icon0
watch icon1

203
204
205
206
207
208
209
210
211
212
const cacheFilename = crypto.createHash('sha1').update(message.toLowerCase()).digest('hex') + '.ogg';
const cachePath = cacheDirectory + cacheFilename;

// Check if the file exists in the cache
try {
    await util.promisify(fs.access)(cachePath, fs.constants.F_OK);
    console.debug(`Reading audio from cache for '${message}'`);
    return fs.createReadStream(cachePath);
}
catch {}
fork icon1
star icon0
watch icon0

+ 2 other calls in file

95
96
97
98
99
100
101
102
103
104
105
106


async function componentsJsonToJs() {
	const data = await componentsPromise;
	const js = `var components = ${JSON.stringify(data)};
if (typeof module !== 'undefined' && module.exports) { module.exports = components; }`;
	return util.promisify(fs.writeFile)(paths.componentsFileJS, js);
}


function watchComponentsAndPlugins() {
	watch(paths.components, parallel(minifyComponents, build));
fork icon0
star icon1
watch icon2

-2
fork icon432
star icon0
watch icon89

+ 3 other calls in file

8
9
10
11
12
13
14
15
16
17
18
19
const Sync = require("sync");
const Fix = require("sync/fix");
const Rebuild = require("sync/rebuild");


const { promisify } = require("util");
const getStatuses = promisify(Blog.getStatuses);


// So the breadcrumbs look like: Settings > Client
client_routes.use(function (req, res, next) {
  res.locals.breadcrumbs.add("Folder", "client");
fork icon69
star icon0
watch icon23