Node.js on Google Cloud

Try It Free View Documentation

Node.js tools to build cloud-native apps, deploy at scale, and analyze data

  • Build planet-scale web apps
  • Use Google’s machine learning APIs with native library support
  • Write serverless apps with ease
  • Create big data analysis apps without learning another language
lovingly-crafted npm modules

Take advantage of our APIs and services using the @google-cloud npm modules and test run our code samples.

1
Install
npm install --save @google-cloud/storage
2
Set up a Google Cloud project
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Storage API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

4
Write your code
/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function uploadFile() {
  // Uploads a local file to the bucket
  await storage.bucket(bucketName).upload(filename, {
    // Support for HTTP requests made with `Accept-Encoding: gzip`
    gzip: true,
    // By setting the option `destination`, you can change the name of the
    // object you are uploading to a bucket.
    metadata: {
      // Enable long-lived HTTP caching headers
      // Use only if the contents of the file will never change
      // (If the contents will change, use cacheControl: 'no-cache')
      cacheControl: 'public, max-age=31536000',
    },
  });

  console.log(`${filename} uploaded to ${bucketName}.`);
}

uploadFile();
1
Install
npm install --save @google-cloud/storage
2
Set up a Google Cloud project
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Storage API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

4
Write your code
/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function uploadFile() {
  // Uploads a local file to the bucket
  await storage.bucket(bucketName).upload(filename, {
    // Support for HTTP requests made with `Accept-Encoding: gzip`
    gzip: true,
    // By setting the option `destination`, you can change the name of the
    // object you are uploading to a bucket.
    metadata: {
      // Enable long-lived HTTP caching headers
      // Use only if the contents of the file will never change
      // (If the contents will change, use cacheControl: 'no-cache')
      cacheControl: 'public, max-age=31536000',
    },
  });

  console.log(`${filename} uploaded to ${bucketName}.`);
}

uploadFile();
1
Install
npm install --save @google-cloud/speech
2
Set up a Google Cloud project
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Speech-to-Text API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

3
Write your code
// Imports the Google Cloud client library
const fs = require('fs');
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const filename = 'Local path to audio file, e.g. /path/to/audio.raw';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
};
const audio = {
  content: fs.readFileSync(filename).toString('base64'),
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file
const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: `, transcription);
1
Install
npm install --save @google-cloud/logging-winston
2
Set up a Google Cloud project
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Logging API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

3
Write your code
const winston = require('winston');

// Imports the Google Cloud client library for Winston
const {LoggingWinston} = require('@google-cloud/logging-winston');

const loggingWinston = new LoggingWinston();

// Create a Winston logger that streams to Stackdriver Logging
// Logs will be written to: "projects/YOUR_PROJECT_ID/logs/winston_log"
const logger = winston.createLogger({
  level: 'info',
  transports: [
    new winston.transports.Console(),
    // Add Stackdriver Logging
    loggingWinston,
  ],
});

// Writes some log entries
logger.error('warp nacelles offline');
logger.info('shields at 99%');
1
Install
npm install --save @google-cloud/bigquery
2
Set up a Google Cloud project
  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the BigQuery API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

3
Write your code
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');

async function queryStackOverflow() {
  // Queries a public Stack Overflow dataset.

  // Create a client
  const bigqueryClient = new BigQuery();

  // The SQL query to run
  const sqlQuery = `SELECT
    CONCAT(
      'https://stackoverflow.com/questions/',
      CAST(id as STRING)) as url,
    view_count
    FROM \`bigquery-public-data.stackoverflow.posts_questions\`
    WHERE tags like '%google-bigquery%'
    ORDER BY view_count DESC
    LIMIT 10`;

  const options = {
    query: sqlQuery,
    // Location must match that of the dataset(s) referenced in the query.
    location: 'US',
  };

  // Run the query
  const [rows] = await bigqueryClient.query(options);

  console.log('Query Results:');
  rows.forEach(row => {
    const url = row['url'];
    const viewCount = row['view_count'];
    console.log(`url: ${url}, ${viewCount} views`);
  });
}
queryStackOverflow();
Node.js quickstarts
Quickly find and debug issues

Stackdriver provides powerful monitoring, logging, and diagnostics to equip you with insight into the health, performance, and availability of cloud-powered apps, enabling you to find and fix issues faster.

Stackdriver
Unified monitoring, logging, and diagnostics for applications on Google Cloud and Amazon Web Services (AWS).
Stackdriver Error Reporting
A walk through of getting an error alert and investigating the error in the Google Cloud Console.
Stackdriver Monitoring, diagnose, and fix
In this video, Aja Hammerly uses Monitoring to find and fix some subtle errors in an example app, and you'll learn how to use Monitoring in your own Google Cloud project.
Learn more
Join our community

Got something to say? Join our community to ask questions, or just chat with the experts at Google who help build Google Cloud and Node.js.