# 开始使用

### 第一步 创建项目，安装依赖

```bash
$ take maty-hello # 创建项目目录并进入
$ npm init # 初始化一个工程
$ npm install maty --save # 安装maty并保存
```

{% hint style="info" %}
&#x20;maty-hello 目录名即项目名，可以改为你的实际项目名
{% endhint %}

### 第二步 建立默认的子目录结构和示例文件，如下

```jsx
maty-hello
├── interceptors
│   └── index.js
├── routers
│   └── hello.js
├── views
│   └── hello.njk
├── node_modules
├── package.json
└── app.js
```

interceptors、routers、views是maty默认加载配置和文件的目录，可以通过[配置](https://tofishes.gitbook.io/maty-js/api-fang-fa/maty-options#basedir)修改。如果是用maty全新构建的项目，建议使用默认即可。

### 第三步 添加服务代码、路由配置、视图文件

1. app.js中添加如下代码<br>

   <pre class="language-javascript" data-title="app.js"><code class="lang-javascript">const maty = require('maty');

   const app = maty();
   const port = 8080;

   app.listen(port, () => {
    const startInfo = `server run at http:\/\/localhost:${port}`;

    console.log(startInfo);
   });
   </code></pre>
2. routers/hello.js中添加如下配置<br>

   <pre class="language-javascript" data-title="hello.js"><code class="lang-javascript">module.exports = {
     '/hello, /hello/:name': {
       handle(data, ctx) {
         return {
           'type': 'world'
         };
       },
       view: 'hello'
     }
   };
   </code></pre>
3. views/hello.njk中添加如下模板代码<br>

   <pre class="language-markup" data-title="hello.njk"><code class="lang-markup">&#x3C;!DOCTYPE html>
   &#x3C;html lang="en">
   &#x3C;head>
     &#x3C;meta charset="UTF-8">
     &#x3C;title>hello page - maty.js&#x3C;/title>
   &#x3C;/head>
   &#x3C;body>
     &#x3C;h3>Hi, this is a hello page with maty.js&#x3C;/h3>
     {% if type %}
     &#x3C;p>get type '{{ type }}' form `router.handle` method.&#x3C;/p>
     {% endif %}

     {% if ctx.param.name %}
     &#x3C;p>get name '{{ ctx.param.name }}' form `ctx.param.name` with inner object ctx.&#x3C;/p>
     {% endif %}
   &#x3C;/body>
   &#x3C;/html>
   </code></pre>

### 最后，启动服务

```bash
$ node app.js
```

分别访问<http://localhost:8080/hello>    [http://localhost:8080/hello/maty](http://localhost:8080/hello/lily) 看看吧！

以上代码托管于 <https://github.com/tofishes/maty-hello>&#x20;
