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')
GitHub: RunOnFlux/flux
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;
+ 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 = [
+ 3 other calls in file
GitHub: porterhq/porter
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() {
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.
GitHub: kubesail/kubesail-agent
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)) {
+ 5 other calls in file
GitHub: all-i-code/bumpr
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)"` }
GitHub: BuilderIO/qwik-build
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";
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",
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) {
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) {
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: {
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();
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) {
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 {}
+ 2 other calls in file
GitHub: Xeltax/padlet
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));
GitHub: davidmerfield/Blot
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");
util.promisify is the most popular function in util (378 examples)