nodejs教程之环境安装及运行_node.js(2)
var end = str.indexOf(close, i)
, js = str.substring(i, end)
, start = i
, include = null
, n = 0;
if ('-' == js[js.length-1]){
js = js.substring(0, js.length - 2);
consumeEOL = true;
}
if (0 == js.trim().indexOf('include')) {
var name = js.trim().slice(7).trim();
if (!filename) throw new Error('filename option is required for includes');
var path = resolveInclude(name, filename);
include = read(path, 'utf8');
include = exports.parse(include, { filename: path, _with: false, open: open, close: close, compileDebug: compileDebug });
buf += "' + (function(){" + include + "})() + '";
js = '';
}
while (~(n = js.indexOf("\n", n))) n++, lineno++;
if (js.substr(0, 1) == ':') js = filtered(js);
if (js) {
if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n';
buf += prefix;
buf += js;
buf += postfix;
}
i += end - start + close.length - 1;
} else if (stri == "\\") {
buf += "\\\\";
} else if (stri == "'") {
buf += "\\'";
} else if (stri == "\r") {
// ignore
} else if (stri == "\n") {
if (consumeEOL) {
consumeEOL = false;
} else {
buf += "\\n";
lineno++;
}
} else {
buf += stri;
}
}
if (false !== options._with) buf += "'); })();\n} \nreturn buf.join('');";
else buf += "');\nreturn buf.join('');";
return buf;
};
就如,我们这里使用到的ejs模板以及express模块,然后我们好奇的走进了ejs的程序看看究竟有何不同
打开,ejs.js后,我们抽一点代码出来看:这段代码我们比较熟悉,他与underscore的模板引擎代码思想一致,都是将模板解析为字符串
然后通过eval或者new Function的方法将之转换为函数,并且传入自己的数据对象好解析
至于具体工作流程,现在我们还不知道,只能放到后面点研究了,好了我们现在进入其他模块
app.js
作为入口文件,app.js扮演着举足轻重的角色:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
我们通过require()命令加载express、http模块,并且会加载routes目录下index user等模板文件
app.set('port', process.env.PORT || 3000)为设置启动时候的端口
app.set('views', __dirname + '/views')为设置存放模板文件的路径,其中__dirname为全局变量,存放当前脚本所在目录,我们这样可以查看: