Before you can use Log Service SDK for Node.js to call the API operations of Log Service, you must install Log Service SDK for Node.js. This topic describes how to install Log Service SDK for Node.js.

Prerequisites

  • Log Service is activated. For more information, see Activate Log Service.
  • An AccessKey pair is created and obtained. An Alibaba Cloud account has permissions to call all API operations. Therefore, security risks may arise if you use the AccessKey pair of an Alibaba Cloud account. We recommend that you log on as a RAM user that has permissions to call API operations or perform routine O&M. For more information, see AccessKey pair.
  • A Node.js development environment is set up. For more information, visit the official website of Node.js.

Installation

  1. Create a project directory and go to the directory.
  2. Run the following initialization command:
    npm init
    Complete the configurations as prompted. After the initialization is complete, the package.json file is created. Example:
    {
      "name": "sls_node",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
  3. Run the following command to install Log Service SDK for Node.js:
    npm install aliyun-sdk
    After the command is run, the package.json file is injected with aliyun-sdk information. Example:
    {
      "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"
      }
    }
  4. Create a project. In the following example, Express is used to create a project.
    1. Run the following command to install Express:
      npm install express
      For more information, see Installing.
    2. Run the following command to install morgan:
      npm install morgan
      For more information, see morgan.
    3. Create an app.js file and add the following code:
      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!'))
    4. Run the following command to start the project:
      node app.js
    After the project is created, the following result is returned:
    Example app listening on port 3000! 

What to do next

Get started with Log Service SDK for Node.js