执行 serverless create --template aws-nodejs --path hello-world
后,就会在当前目录生成一个名为 hello-world
代码目录结构如下:
├── .gitignore
├── handler.js
└── serverless.yml
1. .gitignore
.gitignore 里有3个忽略项,分别如下:
-
node_modules
, 是 Node.js 包管理安装后的目录 -
jspm_packages
,jspm 是 JavaScript 包管理器,是基于 SystemJS 这种通用模块加载器之上的包管理器 -
.serverless
是一个 serverless 部署时的打包生成的目录,当执行serverless deploy
时才会生成
2. handler.js
module.exports.hello = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
}),
};
};
handler.js
是用 --template aws-nodejs
参数生成出来的 js 文件, 代码就是输出一个 JSON。
注:如果我们选用 aws-nodejs-typescript
模块,就会生成 handler.ts
文件。如果你用 Microsoft Azure 服务,也可以选用 azure-nodejs
模板。关于更多项目模板,我后面章节会细讲,请关注哦!
3. serverless.yml
这是 yml 文件里除注释外的代码
service: hello-world
provider:
name: aws
runtime: nodejs8.10
functions:
hello:
handler: handler.hello
这相当于 serverless 的描述文件,介绍了服务名为hello-world
,服务提供商是 aws
,运行环境是nodejs 8.10 版
。
你可能要问,一定要是 nodejs8.10 吗?我要用 Node 10 行不行? 答案是:不行!!!
runtime 目前只支持:java8, nodejs6.10, nodejs8.10, python2.7, python3.6, dotnetcore1.0, dotnetcore2.0, dotnetcore2.1, go1.x
(截止2019-3-9)
第 6 行的 hello:
是调用时的名称,如果改成 hellokenny:
,调用时就要用 serverless invoke -f hellokenny
第 7 行的 handler:
是不能乱改的, 如果你以后发现 Missing "handler" property in function "hello"
,首先就应该检查一下,是不是把 handler:
改错了。
第 7 行的 handler.hello
我们分两部分来讲,点号(.)前面的 handler
是文件名,后面的 hello
是默认函数名。
我们如果把项目根目录的 handler.js
改为 index.js
,那就要把 serverless.yml
里的内容改为 handler: index.hello
。
4. 最后
当我们执行过 serverless deploy
之后就会变成如下目录结构:
├── .gitignore
├── .serverless
│ ├── cloudformation-template-create-stack.json
│ ├── cloudformation-template-update-stack.json
│ ├── hello-world.zip
│ └── serverless-state.json
├── handler.js
└── serverless.yml
-
hello-world.zip
是项目代码文件打包后的压缩文件 -
serverless-state.json
是服务部署后的信息,包含服务名称,服务提供商等信息。部分内容如下:
"service": {
"service": "hello-world",
"serviceObject": {
"name": "hello-world"
},
"provider": {
"stage": "dev",
"region": "us-east-1",
"variableSyntax": "\\${([ ~:a-zA-Z0-9._@'\",\\-\\/\\(\\)]+?)}",
"name": "aws",
"runtime": "nodejs8.10",
"versionFunctions": true,
相关文章
- Serverless 入门(一) - 创建 IAM https://www.jianshu.com/p/9fb731a799e2
- Serverless 入门(二) - HelloWord https://www.jianshu.com/p/ddf2ffda5f63
- Serverless 入门(三)- 初始项目解读 https://www.jianshu.com/p/8baba2a8fe9f
- Serverless 入门(四)- 如何调试 https://www.jianshu.com/p/58d30915de8a
- Serverless 入门(五)- 常用命令 https://www.jianshu.com/p/28f001ea9d9d
- Serverless 入门(六)- DynamoDB 数据库(上) https://www.jianshu.com/p/c313b61d1cbf
- Serverless 入门(七)- DynamoDB 数据库(中) https://www.jianshu.com/p/05e7f4ccd6fe
- Serverless 入门(八)- DynamoDB 数据库(下) https://www.jianshu.com/p/0f9f1561ec46
- Serverless 入门(九)- 权限 https://www.jianshu.com/p/97228749d761