Upload file to Google Storage from memory with Node.js gcloud library

These days was interacting with the Google Cloud Storage(GCS) with the gcloud nodejs library(version 0.31.0) and was surprised that there is no API method to directly upload file from memory. So if you are looking for it - the shorthand is just to use the write stream returned from createWriteStream() on file object:

var gcloud = require("gcloud");
var storage = gcloud.storage({projectId:"dir-bg-scraper"});

var sample_TXT_file = "Hello there,\r\n"+
          "This is sample text file with important info\r\n\r\n"+
          "Best Regards!";

storage.createBucket("dir-bg-scraper", function(err, bucket, apiResponse) {
    if (err===null) {
        // bucket is the newly created "Test-Bucket"
        console.log("'dir-bg-scraper.appspot.com' successfully created!");

        // create 'README.md' file into this bucket
        var new_file = bucket.file("README.md");
        upload_file(new_file, sample_TXT_file, function(err){
            if (err!==null) {
                console.log("Successfully uploaded the file!");
            } else {
                console.error("Failed to uploaded the file..");
            }
        });
        
    } else {
        console.error("Feiled to create 'dir-bg-scraper.appspot.com'..", err);
    }
});

function upload_file(file, contents, callback) {
    // open write stream
    var stream = file.createWriteStream();

    // if there is an error signal back 
    stream.on('error', callback);

    // if everything is successfull signal back
    stream.on('finish', callback);

    // send the contents
    stream.end(contents);       
}

In this sample the "dir-bg-scraper" happens to be the name of my project. So change it with your name. I am accessing the GCS from my local laptop and am running the program in enviromenent already initialized and configured with the project. That is why there is no specific authentication.

Also keep in mind that buckets are shared across aaaaall projects and must be unique. This means that you might need to try multiple times until you come across empty bucket name.

The function that does the work is "upload_file".

Comments

Popular posts from this blog

Data types: Backend DB architecture

Node.js: Optimisations on parsing large JSON file

Back to teaching