-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.mjs
77 lines (66 loc) · 2.62 KB
/
store.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { NFTStorage, File } from "nft.storage";
// The 'mime' npm package helps us set the correct file type on our File objects
import mime from "mime";
// The 'fs' builtin module on Node.js provides access to the file system
import fs from "fs";
// The 'path' module provides helpers for manipulating filesystem paths
import path from "path";
// Paste your NFT.Storage API key into the quotes:
const NFT_STORAGE_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDRlMzU1RjhBMjFkRTM5MTFBNjAzNjVkMTIwQTg2Y0IxNENmRkFGQkMiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY3MDA2NDE2MzQ3MCwibmFtZSI6InRoaXJ1In0.NNgPh41wZ3k2qv4la1cdSriKtdAeplF_uLMl-jXRa-A";
/**
* Reads an image file from `imagePath` and stores an NFT with the given name and description.
* @param {string} imagePath the path to an image file
* @param {string} name a name for the NFT
* @param {string} description a text description for the NFT
*/
async function storeNFT(imagePath, name, description) {
// load the file from disk
const image = await fileFromPath(imagePath);
// create a new NFTStorage client using our API key
const nftstorage = new NFTStorage({ token: NFT_STORAGE_KEY });
// call client.store, passing in the image & metadata
return nftstorage.store({
image,
name,
description,
});
}
/**
* A helper to read a file from a location on disk and return a File object.
* Note that this reads the entire file into memory and should not be used for
* very large files.
* @param {string} filePath the path to a file to store
* @returns {File} a File object containing the file content
*/
async function fileFromPath(filePath) {
const content = await fs.promises.readFile(filePath);
const type = mime.getType(filePath);
return new File([content], path.basename(filePath), { type });
}
/**
* The main entry point for the script that checks the command line arguments and
* calls storeNFT.
*
* To simplify the example, we don't do any fancy command line parsing. Just three
* positional arguments for imagePath, name, and description
*/
async function main() {
const args = process.argv.slice(2);
if (args.length !== 3) {
console.error(
`usage: ${process.argv[0]} ${process.argv[1]} <image-path> <name> <description>`
);
process.exit(1);
}
const [imagePath, name, description] = args;
const result = await storeNFT(imagePath, name, description);
console.log(result);
}
// Don't forget to actually call the main function!
// We can't `await` things at the top level, so this adds
// a .catch() to grab any errors and print them to the console.
main().catch((err) => {
console.error(err);
process.exit(1);
});