如何查看Node.js云功能环境的文件系统性质? [英] How can I see the file system nature of my Node.js Cloud Function environment?

查看:54
本文介绍了如何查看Node.js云功能环境的文件系统性质?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将Cloud Function部署到GCP(用Node.js编写)时,如何查看我的文件系统环境以进行调试?如果我想知道当前目录是什么,或者应用程序旁边有什么文件,怎么办?

When I deploy my Cloud Function to GCP (written in Node.js), how can I see my file system environment for debugging purposes? What if I want to know what my current directory is or what files are present alongside my application?

推荐答案

部署云功能时,将出现完整的Node.js环境.我们可以在其中运行任意Node.js逻辑.这包括日志记录信息,这些信息随后将显示在Stackdriver日志中.因此,我们可以记录当前工作目录路径以及当前目录中所有文件的列表.我们可以将其用作诊断辅助工具.这是一个示例:

When we deploy a Cloud Function, the full Node.js environment is present. We can run arbitrary Node.js logic within. This includes logging information which will then show in the Stackdriver logs. We can thus log our current working directory path as well as a list of all the files in our current directory. We can use this as a diagnostic aid. Here is an example:

const fs = require('fs');
exports.helloWorld = (req, res) => {
  console.log(`CWD: ${process.cwd()}`);
  fs.readdir('.', function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    files.forEach(function (file) {
        console.log(file); 
    });
    res.status(200).send('Done!');
  });
};

您可以将此逻辑合并到自己的应用中进行测试.

You can incorporate this logic in your own apps for testing.

这是一个替代版本,其中显示了所有文件和子目录的递归列表.

And here is an alternate version which shows a recursive listing of all files and sub directories.

const fs = require('fs');
const walk = function(dir) {
  var results = [];
  var list = fs.readdirSync(dir);
  list.forEach(function(file) {
    file = dir + '/' + file;
    var stat = fs.statSync(file);
    if (stat && stat.isDirectory()) { 
      results = results.concat(walk(file));
    } else { 
      results.push(file);
    }
 });
 return results;
}

exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';
  console.log(`CWD: ${process.cwd()}`);
  console.log(`Dir Listing: ${walk('.')}`);
  res.status(200).send('Done!');
};

将上述算法全部归功于 node.js fs.readdir递归目录搜索.

All credit to the above algorithm to node.js fs.readdir recursive directory search.

这篇关于如何查看Node.js云功能环境的文件系统性质?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆