Node.js入门(2)之载入express架构

发表日期:  Creative Commons Licence

摘自http://blog.csdn.net/a1104258464/article/details/50971364

安装express应用生成器

在安装好node.js的前提下,打开控制台,键入如下代码

$npm install express-generator -g #全局安装

控制台需取得管理员权限

express命令

键入$ express -h 显示所有可用的命令行选项

$ express -h

  Usage: express [options] [dir]


  Options:

        --version        output the version number
    -e, --ejs            add ejs engine support
        --pug            add pug engine support
        --hbs            add handlebars engine support
    -H, --hogan          add hogan.js engine support
    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git            add .gitignore
    -f, --force          force on non-empty directory
    -h, --help           output usage information

应用生成

cd至想要放置的目标文件夹目录,键入$ express first -e

该命令的意思是:在当前目录下建立first文件夹 创建一个ejs模板的应用(如果不输入 -e 则生成默认的jade模板)

$ express first -e  
  
   create : first  
   create : first/package.json  
   create : first/app.js  
   create : first/public  
   create : first/public/javascripts  
   create : first/public/images  
   create : first/routes  
   create : first/routes/index.js  
   create : first/routes/users.js  
   create : first/views  
   create : first/views/index.ejs  
   create : first/views/error.ejs  
   create : first/public/stylesheets  
   create : first/public/stylesheets/style.css  
   create : first/bin  
   create : first/bin/www  
  
   install dependencies:  
     > cd first && npm install  
  
   run the app:  
     > SET DEBUG=first:* & npm start  $

然后键入命令

$ cd first         #进入first文件夹  
$ npm install      #安装依赖包 

安装完成后会发现多了个node_modules文件夹 里面放的就是我们安装的模块

注:

  • app.js:启动文件,项目的入口
  • package.json:存储项目的信息及模块依赖,当在 dependencies 中添加依赖的模块时,运行npm install,npm 会检查当前目录下的 package.json,并自动安装所有依赖模块
  • node_modules:存放 package.json 中安装的模块,当你在 package.json 添加依赖的模块并安装后,存放在这个文件夹下
  • public:存放 image、css、js 等文件
  • routes:存放路由文件
  • views:存放视图文件或者说模版文件
  • bin:存放可执行文件

启动应用

键入$ npm start

$ npm start  
  
  
> first@0.0.0 start E:\test\first  
> node ./bin/www  

访问

然后在浏览器中打开 http://localhost:3000/ 网址你可以看到welcome to Express,证明你已经成功了

其他

express官网 http://www.expressjs.com.cn/