NB文档doc.nbjs.ai
快速开始 / 第一个应用

第一个应用

1. 写入口

新建目录,创建 app.js:

export default {
  async fetch() {
    return new Response("hello nb", {
      headers: { "content-type": "text/plain; charset=utf-8" },
    });
  },
};

2. 本地运行

nb app.js --name hello

nb 会先用内置 esbuild 打成单个 ESM,再在 ~/.nb/apps/hello/ 里执行一次自检。成功后会输出:

已加入 hello: http://hello.localhost(GET / → 200)

打开 http://hello.localhost 就能看到结果。

3. 加数据

export default {
  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === "/add") {
      await sql`INSERT INTO note (body, created_at) VALUES (${url.searchParams.get("q")}, ${Date.now()})`;
    }
    const rows = await sql`SELECT id, body FROM note ORDER BY id DESC LIMIT 20`;
    return Response.json(rows);
  },
};

第一次访问会自动创建 app.db。建表可以放在 fetch 里用 CREATE TABLE IF NOT EXISTS,也可以单独写迁移脚本。

4. 远程部署

nb login -r
nb app.js -r

远程控制台会把代码写到 deploy/<name>/,再用 CLI 完成部署,并自动分配 <name>.nbjs.ai。远程部署的权限由 deploy.toml 控制,默认关闭 proc、s3、mqtt 和动态求值。

5. 版本与回退

每次成功部署都会生成版本:

nb history hello
nb rollback hello 3
nb source hello --out ./hello.js

app.db、files/ 和静态资源不参与回退。