nodejs之旅-003-基础知识-全局作用域及全局函数

全局作用域及全局函数

在Nodejs中,一个模块中定义的变量、方法只在该模块中可用,但可以通过exports对象的使用讲起传递到模块外部。但是,仍然存在一个全局作用域,不需要任何模块加载即可使用变量、函数或类。

全局作用域

Nodejs中定义了一个global对象,代表了Nodejs中的全局命名空间,

console.log(global);

{ ArrayBuffer: [Function: ArrayBuffer],
  Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 },
  Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 },
  Uint8ClampedArray: { [Function: Uint8ClampedArray] BYTES_PER_ELEMENT: 1 },
  Int16Array: { [Function: Int16Array] BYTES_PER_ELEMENT: 2 },
  Uint16Array: { [Function: Uint16Array] BYTES_PER_ELEMENT: 2 },
  Int32Array: { [Function: Int32Array] BYTES_PER_ELEMENT: 4 },
  Uint32Array: { [Function: Uint32Array] BYTES_PER_ELEMENT: 4 },
  Float32Array: { [Function: Float32Array] BYTES_PER_ELEMENT: 4 },
  Float64Array: { [Function: Float64Array] BYTES_PER_ELEMENT: 8 },
  DataView: [Function: DataView],
  DTRACE_NET_SERVER_CONNECTION: [Function],
  DTRACE_NET_STREAM_END: [Function],
  DTRACE_NET_SOCKET_READ: [Function],
  DTRACE_NET_SOCKET_WRITE: [Function],
  DTRACE_HTTP_SERVER_REQUEST: [Function],
  DTRACE_HTTP_SERVER_RESPONSE: [Function],
  DTRACE_HTTP_CLIENT_REQUEST: [Function],
  DTRACE_HTTP_CLIENT_RESPONSE: [Function],
  global: [Circular],
  process: 
   { title: 'node',
     version: 'v0.10.32',
     moduleLoadList: 
      [ 'Binding evals',
        'Binding natives',
        'NativeModule events',
        'NativeModule buffer',
        'Binding buffer',
        'NativeModule assert',
        'NativeModule util',
        'NativeModule module',
        'NativeModule path',
        'NativeModule tty',
        'NativeModule net',
        'NativeModule stream',
        'NativeModule _stream_readable',
        'NativeModule _stream_writable',
        'NativeModule _stream_duplex',
        'NativeModule _stream_transform',
        'NativeModule _stream_passthrough',
        'NativeModule timers',
        'Binding timer_wrap',
        'NativeModule _linklist',
        'Binding cares_wrap',
        'Binding tty_wrap',
        'NativeModule vm',
        'NativeModule fs',
        'Binding fs',
        'Binding constants',
        'NativeModule readline',
        'NativeModule console',
        'Binding signal_wrap',
        'NativeModule string_decoder' ],
     versions: 
      { http_parser: '1.0',
        node: '0.10.32',
        v8: '3.14.5.9',
        ares: '1.9.0-DEV',
        uv: '0.10.28',
        zlib: '1.2.3',
        modules: '11',
        openssl: '1.0.1i' },
     arch: 'x64',
     platform: 'darwin',
     argv: [ 'node' ],
     execArgv: [],
     env: 
      { SHELL: '/bin/bash',
        TERM: 'xterm-256color',
        TMPDIR: '/var/folders/8m/338n1zwx6b54drwph5s0hq780000gn/T/',
        Apple_PubSub_Socket_Render: '/private/tmp/com.apple.launchd.u8dfW4kGIc/Render',
        OLDPWD: '/Users/wanq/WebstormProjects/NodejsPro',
        USER: 'wanq',
        SSH_AUTH_SOCK: '/private/tmp/com.apple.launchd.wfqCjimqs6/Listeners',
        __CF_USER_TEXT_ENCODING: '0x1F5:0x19:0x34',
        PATH: '/Users/wanq/DevTools/mongodb/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin',
        PWD: '/Users/wanq/WebstormProjects/NodejsPro/lesson002',
        XPC_FLAGS: '0x0',
        XPC_SERVICE_NAME: '0',
        SHLVL: '1',
        HOME: '/Users/wanq',
        LOGNAME: 'wanq',
        LC_CTYPE: 'zh_CN.UTF-8',
        _: '/usr/local/bin/node' },
     pid: 9514,
     features: 
      { debug: false,
        uv: true,
        ipv6: true,
        tls_npn: true,
        tls_sni: true,
        tls: true },
     _needImmediateCallback: false,
     execPath: '/usr/local/bin/node',
     debugPort: 5858,
     _getActiveRequests: [Function],
     _getActiveHandles: [Function],
     _needTickCallback: [Function],
     reallyExit: [Function],
     abort: [Function],
     chdir: [Function],
     cwd: [Function],
     umask: [Function],
     getuid: [Function],
     setuid: [Function],
     setgid: [Function],
     getgid: [Function],
     getgroups: [Function],
     setgroups: [Function],
     initgroups: [Function],
     _kill: [Function],
     _debugProcess: [Function],
     _debugPause: [Function],
     _debugEnd: [Function],
     hrtime: [Function],
     dlopen: [Function],
     uptime: [Function],
     memoryUsage: [Function],
     binding: [Function],
     _usingDomains: [Function],
     _tickInfoBox: { '0': 1, '1': 0, '2': 0 },
     _events: { SIGWINCH: [Function] },
     domain: null,
     _maxListeners: 10,
     EventEmitter: { [Function: EventEmitter] listenerCount: [Function] },
     _fatalException: [Function],
     _exiting: false,
     assert: [Function],
     config: { target_defaults: [Object], variables: [Object] },
     nextTick: [Function: nextTick],
     _currentTickHandler: [Function: _nextTick],
     _nextDomainTick: [Function: _nextDomainTick],
     _tickCallback: [Function: _tickCallback],
     _tickDomainCallback: [Function: _tickDomainCallback],
     _tickFromSpinner: [Function: _tickFromSpinner],
     maxTickDepth: 1000,
     stdout: [Getter],
     stderr: [Getter],
     stdin: [Getter],
     openStdin: [Function],
     exit: [Function],
     kill: [Function],
     addListener: [Function],
     on: [Function],
     removeListener: [Function] },
  GLOBAL: [Circular],
  root: [Circular],
  Buffer: 
   { [Function: Buffer]
     isEncoding: [Function],
     poolSize: 8192,
     isBuffer: [Function: isBuffer],
     byteLength: [Function],
     concat: [Function] },
  setTimeout: [Function],
  setInterval: [Function],
  clearTimeout: [Function],
  clearInterval: [Function],
  setImmediate: [Function],
  clearImmediate: [Function],
  console: [Getter],
  module: 
   { id: 'repl',
     exports: 
      { writer: [Object],
        _builtinLibs: [Object],
        REPLServer: [Object],
        start: [Function],
        repl: [Object] },
     parent: undefined,
     filename: '/Users/wanq/WebstormProjects/NodejsPro/lesson002/repl',
     loaded: false,
     children: [],
     paths: 
      [ '/Users/wanq/WebstormProjects/NodejsPro/lesson002/repl/node_modules',
        '/Users/wanq/WebstormProjects/NodejsPro/lesson002/node_modules',
        '/Users/wanq/WebstormProjects/NodejsPro/node_modules',
        '/Users/wanq/WebstormProjects/node_modules',
        '/Users/wanq/node_modules',
        '/Users/node_modules',
        '/node_modules' ] },
  require: 
   { [Function: require]
     resolve: [Function],
     main: undefined,
     extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
     registerExtension: [Function],
     cache: {} } }

setTimeout函数与clearTimeout函数

全局函数setTimeout的作用与客户端javascript中的setTimeout函数的作用类似,延迟多少毫秒执行回调函数。
setTimeout(cb, ms, [arg], [...])
前两个参数是必须输入的,后面的事作为回调函数cb的参数。
//5秒后执行callBackFun
var timer = setTimeout(callBackFun,5000);

//取消callBackFun的调用
clearTimeout(timer);

setInterval函数与clearInterval函数

全局函数setInterval的作用与客户端javascript的setInterval函数的作用类似,起定时器的作用,每隔多少秒就执行回调函数。
setInterval(cb, ms, [arg], [...]);
同样的前两个参数是必输的,后面的参数作为回调函数的参数。
//每隔5秒执行回调函数callBackFun
var timer = setInterval(callBackFun, 5000);
//取消callBackFun的调用
clearInterval(timer);

定时器对象的unref方法与ref方法

setTimeout方法与setInterval方法均返回一个定时器对象。定时器对象有unref方法与ref方法。
unref方法是取消调用回调函数。
在调用unref方法后,可以用ref方法恢复定时器调用回调函数。

与模块相关的全局函数及对象

1、使用require函数加载模块

加载模块

var foo = require('../foo.js');

var http = require('http');

testModule.js
/**
 * Created by wanq on 14/11/13.
 */
var testVar = 'This is a variable form testModule.js';
exports.testVar = testVar;

app.js
/**
 * Created by wanq on 14/11/14.
 */
var testModule = require('./testModule.js');
console.log(testModule.testVar);


2、使用require.resolve函数查询完整模块名

require.resolve('./testModule.js');//得到testModule.js的目录及文件名

3、require cache对象

require.cache对象代表了缓存了所有已被加载模块的缓存区

你可能感兴趣的:(nodejs)