文件系统

演示如何访问 Cloud Functions 函数实例的文件系统。

代码示例

C#

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

namespace FileSystem;

public class Function : IHttpFunction
{
    public async Task HandleAsync(HttpContext context)
    {
        string[] files = Directory.GetFiles(".");

        await context.Response.WriteAsync("Files:\n", context.RequestAborted);
        foreach (string file in files)
        {
            await context.Response.WriteAsync($"\t{file}\n", context.RequestAborted);
        }
    }
}

Go

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


// Package tips contains tips for writing Cloud Functions in Go.
package tips

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

func init() {
	functions.HTTP("ListFiles", ListFiles)
}

// ListFiles lists the files in the current directory.
// Uses directory "serverless_function_source_code" as defined in the Go
// Functions Framework Buildpack.
// See https://github.com/GoogleCloudPlatform/buildpacks/blob/56eaad4dfe6c7bd0ecc4a175de030d2cfab9ae1c/cmd/go/functions_framework/main.go#L38.
func ListFiles(w http.ResponseWriter, r *http.Request) {
	files, err := ioutil.ReadDir("./serverless_function_source_code")
	if err != nil {
		http.Error(w, "Unable to read files", http.StatusInternalServerError)
		log.Printf("ioutil.ListFiles: %v", err)
		return
	}
	fmt.Fprintln(w, "Files:")
	for _, f := range files {
		fmt.Fprintf(w, "\t%v\n", f.Name())
	}
}

Java

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class FileSystem implements HttpFunction {

  // Lists the files in the current directory.
  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    File currentDirectory = new File(".");
    File[] files = currentDirectory.listFiles();
    PrintWriter writer = new PrintWriter(response.getWriter());
    writer.println("Files:");
    for (File f : files) {
      writer.printf("\t%s%n", f.getName());
    }
  }
}

Node.js

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

const fs = require('fs');
const functions = require('@google-cloud/functions-framework');

/**
 * HTTP Cloud Function that lists files in the function directory
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
functions.http('listFiles', (req, res) => {
  fs.readdir(__dirname, (err, files) => {
    if (err) {
      console.error(err);
      res.sendStatus(500);
    } else {
      console.log('Files', files);
      res.sendStatus(200);
    }
  });
});

PHP

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


use Psr\Http\Message\ServerRequestInterface;

function listFiles(ServerRequestInterface $request): string
{
    $contents = scandir(__DIR__);

    $output = 'Files:' . PHP_EOL;

    foreach ($contents as $file) {
        $output .= "\t" . $file . PHP_EOL;
    }

    return $output;
}

Python

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import functions_framework


@functions_framework.http
def list_files(request):
    import os
    from os import path

    root = path.dirname(path.abspath(__file__))
    children = os.listdir(root)
    files = [c for c in children if path.isfile(path.join(root, c))]
    return f"Files: {files}"

Ruby

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "functions_framework"

FunctionsFramework.http "concepts_filesystem" do |_request|
  files = Dir.entries "."
  "Files: #{files.join "\n"}"
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器