Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor outputFile APi in async/await #1024

Merged
merged 2 commits into from
Oct 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 10 additions & 19 deletions lib/output-file/index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,27 @@
'use strict'

const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const u = require('universalify').fromPromise
const fs = require('../fs')
const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists

function outputFile (file, data, encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding
encoding = 'utf8'
}

async function outputFile (file, data, encoding = 'utf-8') {
const dir = path.dirname(file)
pathExists(dir, (err, itDoes) => {
if (err) return callback(err)
if (itDoes) return fs.writeFile(file, data, encoding, callback)

mkdir.mkdirs(dir, err => {
if (err) return callback(err)
if (!(await pathExists(dir))) {
await mkdir.mkdirs(dir)
}

fs.writeFile(file, data, encoding, callback)
})
})
return fs.writeFile(file, data, encoding)
}

function outputFileSync (file, ...args) {
const dir = path.dirname(file)
if (fs.existsSync(dir)) {
return fs.writeFileSync(file, ...args)
if (!fs.existsSync(dir)) {
mkdir.mkdirsSync(dir)
}
mkdir.mkdirsSync(dir)

fs.writeFileSync(file, ...args)
}

Expand Down