Node
验证安装:
$ node -v
$ npm -v
进入命令行模式:
$ node
utf-8保存js文件:
"use strict";
console.log("hello world");
运行js文件(js当前目录下):
$ node hello.js
让Node直接为所有js文件开启严格模式:
node --use_strict calc.js
要在模块中对外输出变量,用:
module.exports = function;
module.exports = {hello, hi};
要引入其他模块输出的对象,用:
exports.doGet = doGet;
var get = require("./httpGet");
get.doGet(req, res);
module.exports = {length, substr, find};
var tools = require("./tools");
tools.length()
基本模块
global
js在浏览器中有且仅有一个全局变量,叫window
对象
node.js环境中也有唯一的全局对象,叫global
进入node.js交互环境,可直接输入:global.console
process
process
代表当前node.js进程,通过process
可拿到很多信息:
> process === global.process;
true
> process.version
'v8.10.0'
> process.platform
'linux'
> process.arch
'x64'
> process.cwd();
'/home/xiao'
> process.chdir("/home/xiao/home/MyDocument");
undefined
> process.cwd();
'/home/xiao/home/MyDocument'
process.nextTick()
不是立刻执行,而是要等到下一次事件循环。
process.nextTick(function () {
console.log('111');
});
console.log('222');
//输出:
222
111
响应exit
事件,就可以在程序即将退出时执行某个回调函数:
// 程序即将退出时的回调函数:
process.on('exit', function () {
console.log("bye~");
});
判断js执行环境(根据浏览器和Node环境提供的全局变量名称来判断):
if (typeof(window) === 'undefined') {
console.log('node.js');
} else {
console.log('browser');
}