Skip to content

Commit 640f7b0

Browse files
refactor: Refactor Upload Directory for Improved Reliability (#1867)
* build: Update engines from 8 to 10 Will update to 10 to 12 very soon, but this will prevent eslint issues today * refactor: Refactor Upload Directory for Improved Reliability * chore: Fix file naming * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix: full Node 10 compatiblity * refactor: use defaults from sample comments * fix: Promise-related fixes * fix: add prefix items with dirname Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 5f78907 commit 640f7b0

File tree

2 files changed

+43
-55
lines changed

2 files changed

+43
-55
lines changed

samples/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"license": "Apache-2.0",
55
"author": "Google Inc.",
66
"engines": {
7-
"node": ">=8"
7+
"node": ">=10"
88
},
99
"repository": "googleapis/nodejs-storage",
1010
"private": true,

samples/uploadDirectory.js

Lines changed: 42 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@
1919
// description: Uploads full hierarchy of a local directory to a bucket.
2020
// usage: node files.js upload-directory <bucketName> <directoryPath>
2121

22-
async function main(bucketName, directoryPath) {
22+
function main(
23+
bucketName = 'your-unique-bucket-name',
24+
directoryPath = './local/path/to/directory'
25+
) {
2326
// [START upload_directory]
2427
/**
2528
* TODO(developer): Uncomment the following lines before running the sample.
@@ -36,68 +39,53 @@ async function main(bucketName, directoryPath) {
3639
// Creates a client
3740
const storage = new Storage();
3841

42+
const {promisify} = require('util');
3943
const fs = require('fs');
4044
const path = require('path');
41-
const fileList = [];
4245

43-
async function uploadDirectory() {
44-
// Get a list of files from the specified directory
45-
let dirCtr = 1;
46-
let itemCtr = 0;
47-
const pathDirName = path.dirname(directoryPath);
48-
49-
getFiles(directoryPath);
50-
51-
function getFiles(directory) {
52-
fs.readdir(directory, (err, items) => {
53-
dirCtr--;
54-
itemCtr += items.length;
55-
items.forEach(item => {
56-
const fullPath = path.join(directory, item);
57-
fs.stat(fullPath, (err, stat) => {
58-
itemCtr--;
59-
if (stat.isFile()) {
60-
fileList.push(fullPath);
61-
} else if (stat.isDirectory()) {
62-
dirCtr++;
63-
getFiles(fullPath);
64-
}
65-
if (dirCtr === 0 && itemCtr === 0) {
66-
onComplete();
67-
}
68-
});
69-
});
70-
});
46+
const readdir = promisify(fs.readdir);
47+
const stat = promisify(fs.stat);
48+
49+
async function* getFiles(directory = '.') {
50+
for (const file of await readdir(directory)) {
51+
const fullPath = path.join(directory, file);
52+
const stats = await stat(fullPath);
53+
54+
if (stats.isDirectory()) {
55+
yield* getFiles(fullPath);
56+
}
57+
58+
if (stats.isFile()) {
59+
yield fullPath;
60+
}
7161
}
62+
}
7263

73-
async function onComplete() {
74-
const resp = await Promise.all(
75-
fileList.map(filePath => {
76-
let destination = path.relative(pathDirName, filePath);
77-
// If running on Windows
78-
if (process.platform === 'win32') {
79-
destination = destination.replace(/\\/g, '/');
80-
}
81-
return storage
82-
.bucket(bucketName)
83-
.upload(filePath, {destination})
84-
.then(
85-
uploadResp => ({fileName: destination, status: uploadResp[0]}),
86-
err => ({fileName: destination, response: err})
87-
);
88-
})
89-
);
90-
91-
const successfulUploads =
92-
fileList.length - resp.filter(r => r.status instanceof Error).length;
93-
console.log(
94-
`${successfulUploads} files uploaded to ${bucketName} successfully.`
95-
);
64+
async function uploadDirectory() {
65+
const bucket = storage.bucket(bucketName);
66+
let successfulUploads = 0;
67+
68+
for await (const filePath of getFiles(directoryPath)) {
69+
try {
70+
const dirname = path.dirname(directoryPath);
71+
const destination = path.relative(dirname, filePath);
72+
73+
await bucket.upload(filePath, {destination});
74+
75+
console.log(`Successfully uploaded: ${filePath}`);
76+
successfulUploads++;
77+
} catch (e) {
78+
console.error(`Error uploading ${filePath}:`, e);
79+
}
9680
}
81+
82+
console.log(
83+
`${successfulUploads} files uploaded to ${bucketName} successfully.`
84+
);
9785
}
9886

9987
uploadDirectory().catch(console.error);
10088
// [END upload_directory]
10189
}
10290

103-
main(...process.argv.slice(2)).catch(console.error);
91+
main(...process.argv.slice(2));

0 commit comments

Comments
 (0)