Skip to content

Commit

Permalink
refactor: use fs promises
Browse files Browse the repository at this point in the history
  • Loading branch information
alumni committed Dec 21, 2024
1 parent 19a6954 commit 88a3d93
Show file tree
Hide file tree
Showing 16 changed files with 138 additions and 180 deletions.
4 changes: 2 additions & 2 deletions gulpfile.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Gulpclass, Task, SequenceTask, MergedTask } from "gulpclass";

import fs from "fs";
import fs from "fs/promises";
import gulp from "gulp";
import del from "del";
import shell from "gulp-shell";
Expand Down Expand Up @@ -174,7 +174,7 @@ export class Gulpfile {
`export {\n ${cjsKeys.join(",\n ")}\n};\n` +
'export default TypeORM;\n';

fs.writeFileSync(`${buildDir}/index.mjs`, indexMjsContent, "utf8");
await fs.writeFile(`${buildDir}/index.mjs`, indexMjsContent, "utf8");
}

/**
Expand Down
32 changes: 0 additions & 32 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,11 @@
],
"devDependencies": {
"@tsconfig/node16": "^16.1.1",
"@types/app-root-path": "^1.2.4",
"@types/chai": "^4.3.4",
"@types/chai-as-promised": "^7.1.5",
"@types/debug": "^4.1.7",
"@types/gulp-rename": "^2.0.6",
"@types/gulp-sourcemaps": "^0.0.38",
"@types/mkdirp": "^1.0.2",
"@types/mocha": "^10.0.1",
"@types/node": "^18.13.0",
"@types/sha.js": "^2.4.0",
Expand Down Expand Up @@ -230,7 +228,6 @@
"debug": "^4.3.4",
"dotenv": "^16.0.3",
"glob": "^10.4.5",
"mkdirp": "^2.1.3",
"sha.js": "^2.4.11",
"tslib": "^2.5.0",
"uuid": "^9.0.0",
Expand Down
29 changes: 14 additions & 15 deletions src/commands/CommandUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as fs from "fs"
import * as path from "path"
import mkdirp from "mkdirp"
import fs from "fs/promises"
import path from "path"
import { TypeORMError } from "../error"
import { DataSource } from "../data-source"
import { InstanceChecker } from "../util/InstanceChecker"
Expand Down Expand Up @@ -67,7 +66,7 @@ export class CommandUtils {
* Creates directories recursively.
*/
static createDirectories(directory: string) {
return mkdirp(directory)
return fs.mkdir(directory, { recursive: true })
}

/**
Expand All @@ -79,26 +78,26 @@ export class CommandUtils {
override: boolean = true,
): Promise<void> {
await CommandUtils.createDirectories(path.dirname(filePath))
return new Promise<void>((ok, fail) => {
if (override === false && fs.existsSync(filePath)) return ok()

fs.writeFile(filePath, content, (err) => (err ? fail(err) : ok()))
})
if (override === false && (await CommandUtils.fileExists(filePath))) {
return
}
await fs.writeFile(filePath, content)
}

/**
* Reads everything from a given file and returns its content as a string.
*/
static async readFile(filePath: string): Promise<string> {
return new Promise<string>((ok, fail) => {
fs.readFile(filePath, (err, data) =>
err ? fail(err) : ok(data.toString()),
)
})
return (await fs.readFile(filePath)).toString()
}

static async fileExists(filePath: string) {
return fs.existsSync(filePath)
try {
await fs.access(filePath, fs.constants.F_OK)
return true
} catch {
return false
}
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/driver/better-sqlite3/BetterSqlite3Driver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import mkdirp from "mkdirp"
import fs from "fs/promises"
import path from "path"
import { DriverPackageNotInstalledError } from "../../error"
import { PlatformTools } from "../../platform/PlatformTools"
Expand Down Expand Up @@ -187,7 +187,7 @@ export class BetterSqlite3Driver extends AbstractSqliteDriver {
* Auto creates database directory if it does not exist.
*/
protected async createDatabaseDirectory(dbPath: string): Promise<void> {
await mkdirp(dbPath)
await fs.mkdir(dbPath, { recursive: true })
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/driver/sqlite/SqliteDriver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import mkdirp from "mkdirp"
import fs from "fs/promises"
import path from "path"
import { DriverPackageNotInstalledError } from "../../error/DriverPackageNotInstalledError"
import { SqliteQueryRunner } from "./SqliteQueryRunner"
Expand Down Expand Up @@ -203,7 +203,7 @@ export class SqliteDriver extends AbstractSqliteDriver {
* Auto creates database directory if it does not exist.
*/
protected async createDatabaseDirectory(fullPath: string): Promise<void> {
await mkdirp(path.dirname(fullPath))
await fs.mkdir(path.dirname(fullPath), { recursive: true })
}

/**
Expand Down
11 changes: 3 additions & 8 deletions src/platform/PlatformTools.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as path from "path"
import * as fs from "fs"
import path from "path"
import fs from "fs"
import dotenv from "dotenv"
import chalk from "chalk"
import { highlight, Theme } from "cli-highlight"
Expand Down Expand Up @@ -182,12 +182,7 @@ export class PlatformTools {
}

static async writeFile(path: string, data: any): Promise<void> {
return new Promise<void>((ok, fail) => {
fs.writeFile(path, data, (err) => {
if (err) fail(err)
ok()
})
})
return fs.promises.writeFile(path, data)
}

/**
Expand Down
60 changes: 23 additions & 37 deletions src/util/ImportUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fs from "fs"
import fs from "fs/promises"
import path from "path"
import { pathToFileURL } from "url"

Expand Down Expand Up @@ -39,45 +39,31 @@ export async function importOrRequireFile(
return tryToRequire()
}

function getNearestPackageJson(filePath: string): Promise<object | null> {
return new Promise((accept) => {
let currentPath = filePath
async function getNearestPackageJson(filePath: string): Promise<object | null> {
let currentPath = filePath

function searchPackageJson() {
const nextPath = path.dirname(currentPath)
while (currentPath !== path.dirname(currentPath)) {
currentPath = path.dirname(currentPath)
const potentialPackageJson = path.join(currentPath, "package.json")

if (currentPath === nextPath)
// the top of the file tree is reached
accept(null)
else {
currentPath = nextPath
const potentialPackageJson = path.join(
currentPath,
"package.json",
)

fs.stat(potentialPackageJson, (err, stats) => {
if (err != null) searchPackageJson()
else if (stats.isFile()) {
fs.readFile(
potentialPackageJson,
"utf8",
(err, data) => {
if (err != null) accept(null)
else {
try {
accept(JSON.parse(data))
} catch (err) {
accept(null)
}
}
},
)
} else searchPackageJson()
})
try {
const stats = await fs.stat(potentialPackageJson)
if (stats.isFile()) {
try {
return JSON.parse(
await fs.readFile(potentialPackageJson, "utf8"),
)
} catch {
return null
}
} else {
continue
}
} catch {
continue
}
}

searchPackageJson()
})
// the top of the file tree is reached
return null
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { promises as fs } from "fs"
import fs from "fs/promises"
import { expect } from "chai"
import { DataSourceOptions } from "../../../src/data-source/DataSourceOptions"
import { ConnectionOptionsReader } from "../../../src/connection/ConnectionOptionsReader"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { User } from "./entity/User"
import { filepathToName } from "../../../../src/util/PathUtils"
import rimraf from "rimraf"
import path from "path"
import fs from "fs"
import fs from "fs/promises"
import appRoot from "app-root-path"

const VALID_NAME_REGEX = /^(?!sqlite_).{1,63}$/
Expand Down Expand Up @@ -104,9 +104,13 @@ describe("multi-database > basic-functionality", () => {
)!.groups!["filename"],
)

expect(fs.existsSync(expectedMainPath)).to.be.true
expect(fs.existsSync(attachAnswerPath)).to.be.true
expect(fs.existsSync(attachCategoryPath)).to.be.true
await expect(fs.access(expectedMainPath, fs.constants.F_OK))
.to.not.be.rejected
await expect(fs.access(attachAnswerPath, fs.constants.F_OK))
.to.not.be.rejected
await expect(
fs.access(attachCategoryPath, fs.constants.F_OK),
).to.not.be.rejected
}),
))

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import "reflect-metadata"
import fs from "fs/promises"
import { expect } from "chai"
import sinon from "sinon"
import {
closeTestingConnections,
createTestingConnections,
Expand All @@ -11,11 +12,7 @@ import { User } from "./entity/User"
import { Category } from "./entity/Category"
import { Post } from "./entity/Post"
import { Photo } from "./entity/Photo"
import sinon from "sinon"
import { FileLogger } from "../../../../src"
import { promisify } from "util"
import fs from "fs"
import { readFile, unlink } from "fs"

describe("repository > find options", () => {
let connections: DataSource[]
Expand Down Expand Up @@ -256,9 +253,9 @@ describe("repository > find options > comment", () => {
beforeEach(() => reloadTestingDatabases(connections))
after(async () => {
await closeTestingConnections(connections)
if (fs.existsSync(logPath)) {
await promisify(unlink)(logPath)
}
try {
fs.unlink(logPath)
} catch {}
})

it("repository should insert comment", () =>
Expand All @@ -268,7 +265,7 @@ describe("repository > find options > comment", () => {
.getRepository(User)
.find({ comment: "This is a query comment." })

const logs = await promisify(readFile)(logPath)
const logs = await fs.readFile(logPath)
const lines = logs.toString().split("\n")
const lastLine = lines[lines.length - 2] // last line is blank after newline
// remove timestamp and prefix
Expand Down
4 changes: 2 additions & 2 deletions test/functional/sqljs/load.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import "reflect-metadata"
import * as fs from "fs"
import fs from "fs/promises"
import { expect } from "chai"
import {
closeTestingConnections,
Expand Down Expand Up @@ -41,7 +41,7 @@ describe("sqljs driver > load", () => {
const exportedDatabase =
dataSource.sqljsManager.exportDatabase()
expect(exportedDatabase).not.to.be.undefined
const originalFileContent = fs.readFileSync(
const originalFileContent = await fs.readFile(
"test/functional/sqljs/sqlite/test.sqlite",
)
expect(exportedDatabase.length).to.equal(
Expand Down
Loading

0 comments on commit 88a3d93

Please sign in to comment.