Skip to content

Commit

Permalink
refactor: remove util.promisify calls
Browse files Browse the repository at this point in the history
  • Loading branch information
barisusakli committed Aug 14, 2020
1 parent 45c8de1 commit 0189945
Show file tree
Hide file tree
Showing 18 changed files with 50 additions and 108 deletions.
5 changes: 1 addition & 4 deletions src/cli/reset.js
Expand Up @@ -4,9 +4,6 @@ require('colors');
const path = require('path');
const winston = require('winston');
const fs = require('fs');
const util = require('util');

const fsAccessAsync = util.promisify(fs.access);

const db = require('../database');
const events = require('../events');
Expand Down Expand Up @@ -100,7 +97,7 @@ async function resetSettings() {

async function resetTheme(themeId) {
try {
await fsAccessAsync(path.join(dirname, 'node_modules', themeId, 'package.json'));
await fs.promises.access(path.join(dirname, 'node_modules', themeId, 'package.json'));
} catch (err) {
winston.warn('[reset] Theme `%s` is not installed on this forum', themeId);
throw new Error('theme-not-found');
Expand Down
4 changes: 1 addition & 3 deletions src/controllers/admin/themes.js
Expand Up @@ -2,8 +2,6 @@

const path = require('path');
const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);

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

Expand All @@ -17,7 +15,7 @@ themesController.get = async function (req, res, next) {

let themeConfig;
try {
themeConfig = await readFileAsync(themeConfigPath, 'utf8');
themeConfig = await fs.promises.readFile(themeConfigPath, 'utf8');
themeConfig = JSON.parse(themeConfig);
} catch (err) {
if (err.code === 'ENOENT') {
Expand Down
9 changes: 3 additions & 6 deletions src/controllers/admin/uploads.js
Expand Up @@ -4,9 +4,6 @@ const path = require('path');
const nconf = require('nconf');
const mime = require('mime');
const fs = require('fs');
const util = require('util');
const readdirAsync = util.promisify(fs.readdir);
const statAsync = util.promisify(fs.stat);

const meta = require('../../meta');
const posts = require('../../posts');
Expand All @@ -27,7 +24,7 @@ uploadsController.get = async function (req, res, next) {
const itemsPerPage = 20;
const page = parseInt(req.query.page, 10) || 1;
try {
let files = await readdirAsync(currentFolder);
let files = await fs.promises.readdir(currentFolder);
files = files.filter(filename => filename !== '.gitignore');
const itemCount = files.length;
var start = Math.max(0, (page - 1) * itemsPerPage);
Expand Down Expand Up @@ -91,10 +88,10 @@ async function filesToData(currentDir, files) {
}

async function getFileData(currentDir, file) {
const stat = await statAsync(path.join(currentDir, file));
const stat = await fs.promises.stat(path.join(currentDir, file));
let filesInDir = [];
if (stat.isDirectory()) {
filesInDir = await readdirAsync(path.join(currentDir, file));
filesInDir = await fs.promises.readdir(path.join(currentDir, file));
}
const url = nconf.get('upload_url') + currentDir.replace(nconf.get('upload_path'), '') + '/' + file;
return {
Expand Down
8 changes: 2 additions & 6 deletions src/emailer.js
Expand Up @@ -9,10 +9,6 @@ const htmlToText = require('html-to-text');
const url = require('url');
const path = require('path');
const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);

const _ = require('lodash');
const jwt = require('jsonwebtoken');

Expand Down Expand Up @@ -47,7 +43,7 @@ Emailer.getTemplates = async function (config) {

const templates = await Promise.all(emails.map(async (email) => {
const path = email.replace(emailsPath, '').substr(1).replace('.tpl', '');
const original = await readFileAsync(email, 'utf8');
const original = await fs.promises.readFile(email, 'utf8');

return {
path: path,
Expand Down Expand Up @@ -316,7 +312,7 @@ async function buildCustomTemplates(config) {
const compiled = await Benchpress.precompile(source, {
minify: global.env !== 'development',
});
await writeFileAsync(template.fullpath.replace(/\.tpl$/, '.js'), compiled);
await fs.promises.writeFile(template.fullpath.replace(/\.tpl$/, '.js'), compiled);
}));

Benchpress.flush();
Expand Down
27 changes: 9 additions & 18 deletions src/file.js
Expand Up @@ -7,15 +7,6 @@ const winston = require('winston');
const mkdirp = require('mkdirp');
const mime = require('mime');
const graceful = require('graceful-fs');
const util = require('util');

const readdirAsync = util.promisify(fs.readdir);
const copyFileAsync = util.promisify(fs.copyFile);
const writeFleAsync = util.promisify(fs.writeFile);
const statAsync = util.promisify(fs.stat);
const unlinkAsync = util.promisify(fs.unlink);
const linkAsync = util.promisify(fs.link);
const symlinkAsync = util.promisify(fs.symlink);

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

Expand All @@ -36,7 +27,7 @@ file.saveFileToLocal = async function (filename, folder, tempPath) {

winston.verbose('Saving file ' + filename + ' to : ' + uploadPath);
await mkdirp(path.dirname(uploadPath));
await copyFileAsync(tempPath, uploadPath);
await fs.promises.copyFile(tempPath, uploadPath);
return {
url: '/assets/uploads/' + (folder ? folder + '/' : '') + filename,
path: uploadPath,
Expand All @@ -47,7 +38,7 @@ file.base64ToLocal = async function (imageData, uploadPath) {
const buffer = Buffer.from(imageData.slice(imageData.indexOf('base64') + 7), 'base64');
uploadPath = path.join(nconf.get('upload_path'), uploadPath);

await writeFleAsync(uploadPath, buffer, {
await fs.promises.writeFile(uploadPath, buffer, {
encoding: 'base64',
});
return uploadPath;
Expand Down Expand Up @@ -86,7 +77,7 @@ file.allowedExtensions = function () {

file.exists = async function (path) {
try {
await statAsync(path);
await fs.promises.stat(path);
} catch (err) {
if (err.code === 'ENOENT') {
return false;
Expand Down Expand Up @@ -114,7 +105,7 @@ file.delete = async function (path) {
return;
}
try {
await unlinkAsync(path);
await fs.promises.unlink(path);
} catch (err) {
winston.warn(err);
}
Expand All @@ -126,9 +117,9 @@ file.link = async function link(filePath, destPath, relative) {
}

if (process.platform === 'win32') {
await linkAsync(filePath, destPath);
await fs.promises.link(filePath, destPath);
} else {
await symlinkAsync(filePath, destPath, 'file');
await fs.promises.symlink(filePath, destPath, 'file');
}
};

Expand All @@ -138,7 +129,7 @@ file.linkDirs = async function linkDirs(sourceDir, destDir, relative) {
}

const type = (process.platform === 'win32') ? 'junction' : 'dir';
await symlinkAsync(sourceDir, destDir, type);
await fs.promises.symlink(sourceDir, destDir, type);
};

file.typeToExtension = function (type) {
Expand All @@ -151,10 +142,10 @@ file.typeToExtension = function (type) {

// Adapted from http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search
file.walk = async function (dir) {
const subdirs = await readdirAsync(dir);
const subdirs = await fs.promises.readdir(dir);
const files = await Promise.all(subdirs.map(async (subdir) => {
const res = path.resolve(dir, subdir);
return (await statAsync(res)).isDirectory() ? file.walk(res) : res;
return (await fs.promises.stat(res)).isDirectory() ? file.walk(res) : res;
}));
return files.reduce((a, f) => a.concat(f), []);
};
Expand Down
11 changes: 4 additions & 7 deletions src/image.js
Expand Up @@ -5,9 +5,6 @@ const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const winston = require('winston');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);

const file = require('./file');
const plugins = require('./plugins');
Expand Down Expand Up @@ -46,7 +43,7 @@ image.resizeImage = async function (data) {
});
} else {
const sharp = requireSharp();
const buffer = await readFileAsync(data.path);
const buffer = await fs.promises.readFile(data.path);
const sharpImage = sharp(buffer, {
failOnError: true,
});
Expand Down Expand Up @@ -93,7 +90,7 @@ image.stripEXIF = async function (path) {
return;
}
try {
const buffer = await readFileAsync(path);
const buffer = await fs.promises.readFile(path);
const sharp = requireSharp();
await sharp(buffer, { failOnError: true }).rotate().toFile(path);
} catch (err) {
Expand All @@ -111,7 +108,7 @@ image.checkDimensions = async function (path) {
};

image.convertImageToBase64 = async function (path) {
return await readFileAsync(path, 'base64');
return await fs.promises.readFile(path, 'base64');
};

image.mimeFromBase64 = function (imageData) {
Expand All @@ -132,7 +129,7 @@ image.writeImageDataToTempFile = async function (imageData) {

const buffer = Buffer.from(imageData.slice(imageData.indexOf('base64') + 7), 'base64');

await writeFileAsync(filepath, buffer, { encoding: 'base64' });
await fs.promises.writeFile(filepath, buffer, { encoding: 'base64' });
return filepath;
};

Expand Down
9 changes: 3 additions & 6 deletions src/languages.js
Expand Up @@ -3,17 +3,14 @@
const fs = require('fs');
const path = require('path');

const util = require('util');
const readFileAsync = util.promisify(fs.readFile);

const Languages = module.exports;
const languagesPath = path.join(__dirname, '../build/public/language');

const files = fs.readdirSync(path.join(__dirname, '../public/vendor/jquery/timeago/locales'));
Languages.timeagoCodes = files.filter(f => f.startsWith('jquery.timeago')).map(f => f.split('.')[2]);

Languages.get = async function (language, namespace) {
const data = await readFileAsync(path.join(languagesPath, language, namespace + '.json'), 'utf8');
const data = await fs.promises.readFile(path.join(languagesPath, language, namespace + '.json'), 'utf8');
return JSON.parse(data) || {};
};

Expand All @@ -23,7 +20,7 @@ Languages.listCodes = async function () {
return codeCache;
}
try {
const file = await readFileAsync(path.join(languagesPath, 'metadata.json'), 'utf8');
const file = await fs.promises.readFile(path.join(languagesPath, 'metadata.json'), 'utf8');
const parsed = JSON.parse(file);

codeCache = parsed.languages;
Expand All @@ -47,7 +44,7 @@ Languages.list = async function () {
let languages = await Promise.all(codes.map(async function (folder) {
try {
const configPath = path.join(languagesPath, folder, 'language.json');
const file = await readFileAsync(configPath, 'utf8');
const file = await fs.promises.readFile(configPath, 'utf8');
const lang = JSON.parse(file);
return lang;
} catch (err) {
Expand Down
7 changes: 2 additions & 5 deletions src/meta/cacheBuster.js
Expand Up @@ -4,9 +4,6 @@ const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const winston = require('winston');
const util = require('util');
const writeFileAsync = util.promisify(fs.writeFile);
const readFileAsync = util.promisify(fs.readFile);

const filePath = path.join(__dirname, '../../build/cache-buster');

Expand All @@ -19,15 +16,15 @@ function generate() {

exports.write = async function write() {
await mkdirp(path.dirname(filePath));
await writeFileAsync(filePath, generate());
await fs.promises.writeFile(filePath, generate());
};

exports.read = async function read() {
if (cached) {
return cached;
}
try {
const buster = await readFileAsync(filePath, 'utf8');
const buster = await fs.promises.readFile(filePath, 'utf8');
if (!buster || buster.length !== 11) {
winston.warn('[cache-buster] cache buster string invalid: expected /[a-z0-9]{11}/, got `' + buster + '`');
return generate();
Expand Down
4 changes: 1 addition & 3 deletions src/meta/dependencies.js
Expand Up @@ -2,8 +2,6 @@

const path = require('path');
const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);

const semver = require('semver');
const winston = require('winston');
Expand Down Expand Up @@ -34,7 +32,7 @@ const pluginNamePattern = /^(@.*?\/)?nodebb-(theme|plugin|widget|rewards)-.*$/;

Dependencies.checkModule = async function (moduleName) {
try {
let pkgData = await readFileAsync(path.join(__dirname, '../../node_modules/', moduleName, 'package.json'), 'utf8');
let pkgData = await fs.promises.readFile(path.join(__dirname, '../../node_modules/', moduleName, 'package.json'), 'utf8');
pkgData = Dependencies.parseModuleData(moduleName, pkgData);

const satisfies = Dependencies.doesSatisfy(pkgData, pkg.dependencies[moduleName]);
Expand Down
11 changes: 4 additions & 7 deletions src/meta/languages.js
@@ -1,17 +1,14 @@
'use strict';

const _ = require('lodash');
const nconf = require('nconf');
const path = require('path');
const fs = require('fs');
const util = require('util');
let mkdirp = require('mkdirp');
mkdirp = mkdirp.hasOwnProperty('native') ? mkdirp : util.promisify(mkdirp);
const rimraf = require('rimraf');
const _ = require('lodash');

const rimrafAsync = util.promisify(rimraf);
const writeFileAsync = util.promisify(fs.writeFile);
const readFileAsync = util.promisify(fs.readFile);

const file = require('../file');
const Plugins = require('../plugins');
Expand Down Expand Up @@ -55,7 +52,7 @@ async function getTranslationMetadata() {
languages: languages,
namespaces: namespaces,
};
await writeFileAsync(path.join(buildLanguagesPath, 'metadata.json'), JSON.stringify(result));
await fs.promises.writeFile(path.join(buildLanguagesPath, 'metadata.json'), JSON.stringify(result));
return result;
}

Expand All @@ -64,7 +61,7 @@ async function writeLanguageFile(language, namespace, translations) {
const filePath = path.join(buildLanguagesPath, language, namespace + '.json');

await mkdirp(path.dirname(filePath));
await writeFileAsync(filePath, JSON.stringify(translations, null, dev ? 2 : 0));
await fs.promises.writeFile(filePath, JSON.stringify(translations, null, dev ? 2 : 0));
}

// for each language and namespace combination,
Expand Down Expand Up @@ -124,7 +121,7 @@ async function addPlugin(translations, pluginData, lang, namespace) {

async function assignFileToTranslations(translations, path) {
try {
const fileData = await readFileAsync(path, 'utf8');
const fileData = await fs.promises.readFile(path, 'utf8');
Object.assign(translations, JSON.parse(fileData));
} catch (err) {
if (err.code !== 'ENOENT') {
Expand Down
7 changes: 2 additions & 5 deletions src/meta/logs.js
Expand Up @@ -2,17 +2,14 @@

const path = require('path');
const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);
const truncateAsync = util.promisify(fs.truncate);
const Logs = module.exports;

Logs.path = path.resolve(__dirname, '../../logs/output.log');

Logs.get = async function () {
return await readFileAsync(Logs.path, 'utf-8');
return await fs.promises.readFile(Logs.path, 'utf-8');
};

Logs.clear = async function () {
return await truncateAsync(Logs.path, 0);
return await fs.promises.truncate(Logs.path, 0);
};

0 comments on commit 0189945

Please sign in to comment.