使用Node.js SDK进行日志服务各类操作前,您需要安装Node.js SDK。本文介绍Node.js SDK的安装方法。
注意事项
日志服务Node.js SDK基于JavaScript开发,暂不支持TS(TypeScript)。
安装SDK
- 创建项目目录,并进入该目录。
- 执行以下命令初始化。
按照向导提示进行配置。初始化完成后,会自动创建一个
package.json文件。其文件内容示例如下:
{
"name": "sls_node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
- 执行以下命令安装Node.js SDK。
npm install aliyun-sdk
如果使用npm遇到网络问题,建议使用淘宝提供的npm镜像。
执行完成后,
package.json文件已注入aliyun-sdk信息。其文件内容示例如下:
{
"name": "sls_node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"aliyun-sdk": "^1.12.3"
}
}
- 搭建项目。本文以使用Express搭建项目为例。
- 执行以下命令安装Express。
- 执行以下命令安装morgan。
npm install morgan
更多信息,请参见
morgan。
- 创建app.js文件并写入以下代码。
var express = require('express')
var morgan = require('morgan')
var app = express()
const logger = morgan(function (tokens, req, res) {
return [
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'), '-',
tokens['response-time'](req, res), 'ms'
].join(' ')
})
app.use(logger)
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(3000, () => console.log('Example app listening on port 3000!'))
- 执行以下命令启动项目。
完成后,返回以下结果。
Example app listening on port 3000!