Node js global variables. NodeJS. Global object. Reading and writing files

In a node, you can set global variables using the "global" or "GLOBAL" object:

GLOBAL._ = require("underscore"); // but you "shouldn"t" do this! (see note below)

or more useful...

GLOBAL.window = GLOBAL; // like in the browser

From the node, you can see that they are stitched together:

Node-v0.6.6/src/node.js:28:global = this; 128: global.GLOBAL = global;

In the above code, "this" is the global context. With the commonJS module (which node uses), this "object" inside the module (i.e. "your code") is NOT the global context. For proof of this, see below where I spew out "this" object and then the giant "GLOBAL" object.

Console.log("\nTHIS:"); console.log(this); console.log("\nGLOBAL:"); console.log(global); /* outputs ... THIS: {} GLOBAL: ( ArrayBuffer: , Int8Array: ( BYTES_PER_ELEMENT: 1 ), Uint8Array: ( BYTES_PER_ELEMENT: 1 ), Int16Array: ( BYTES_PER_ELEMENT: 2 ), Uint16Array: ( BYTES_PER_ELEMENT: 2 ), Int32Array: ( BYTES_PER_ELEMENT: 4 ), Uint32Array: ( BYTES_PER _ELEMENT: 4 ), Float32Array: ( BYTES_PER_ELEMENT: 4 ), Float64Array: ( BYTES_PER_ELEMENT: 8 ), DataView: , global: , process: ( EventEmitter: , title: "node", assert: , version: "v0.6.5", _tickCallback: , moduleLoadList: [ "Binding evals", "Binding natives", "NativeModule events", "NativeModule buffer", "Binding buffer", "NativeModule assert", "NativeModule util", "NativeModule path", "NativeModule module", "NativeModule fs", "Binding fs", "Binding constants", "NativeModule stream", "NativeModule console", "Binding tty_wrap", "NativeModule tty", "NativeModule net", "NativeModule timers", "Binding timer_wrap", "NativeModule _linklist" ], versions: ( node: "0.6.5", v8: "3.6.6.11", ares: "1.7.5-DEV", uv: "0.6", openssl: "0.9.8n" ), nextTick: , stdout: , arch: "x64", stderr: , platform: "darwin", argv: [ "node", "/workspace/zd/zgap/darwin-js/index.js" ], stdin: , env: ( TERM_PROGRAM: "iTerm.app", "COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET": "/tmp/launch-nNl1vo/ServiceProcessSocket", TERM: "xterm", SHELL: "/bin/bash", TMPDIR: "/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/", Apple_PubSub_Socket_Render: "/tmp/launch-9Ga0PT/Render", USER: "ddopson", COMMAND_MODE: "unix2003", SSH_AUTH_SOCK: "/tmp/launch -sD905b/Listeners", __CF_USER_TEXT_ENCODING: "0x12D732E7:0:0", PATH: "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11 /bin", PWD: "/workspace/zd/zgap/darwin-js", LANG: "en_US.UTF-8", ITERM_PROFILE: "Default", SHLVL: "1", COLORFGBG: "7;0", HOME : "/Users/ddopson", ITERM_SESSION_ID: "w0t0p0", LOGNAME: "ddopson", DISPLAY: "/tmp/launch-l9RQXI/org.x:0", OLDPWD: "/workspace/zd/zgap/darwin-js /external", _: "./index.js"), openStdin: , exit: , pid: 10321, features: ( debug: false, uv: true, ipv6: true, tls_npn: false, tls_sni: true, tls: true ), kill: , execPath: "/usr/local/bin/node", addListener: , _needTickCallback: , on: , removeListener: , reallyExit: , chdir: , debug: , error: , cwd: , watchFile: , umask : , getuid: , unwatchFile: , mixin: , setuid: , setgid: , createChildProcess: , getgid: , inherits: , _kill: , _byteLength: , mainModule: ( id: ". ", exports: (), parent: null, filename: "/workspace/zd/zgap/darwin-js/index.js", loaded: false, exited: false, children: , paths: ), _debugProcess: , dlopen: , uptime: , memoryUsage: , uvCounters: , binding: ), GLOBAL: , root: , Buffer: ( poolSize: 8192, isBuffer: , byteLength: , _charsWritten: 8 ), setTimeout: , setInterval: , clearTimeout: , clearInterval: , console: , window: , navigator: () ) */

**Note: Regarding the "GLOBAL._" setting, in general you should just do var _ = require("underscore"); . Yes, you do this in every file that uses underscore, just like in Java you do import com.foo.bar; . This makes it easier to determine what your code is doing because the links between files are "explicit". Mildly annoying, but good. This is a sermon.

There is an exception to every rule. I had exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "config" files that were mostly JSON, but were "written in JS" to add a little more flexibility. There were no "require" statements in such config files, but I wanted them to have access to underscore (the ENTIRE system was based on underscore and underscore patterns), so I would set "GLOBAL._" before evaluating "config". So yes, for every rule there is an exception somewhere. But you have a good reason, not just "I'm tired of typing" so I want to break the agreement."

JavaScript has a special object called a Global Object, it and all of its attributes can be accessed anywhere in the program, a global variable.

A JavaScript browser is usually a global window object, a Node.js global object is a global object, all global variables (except the global self) are owned by the global object.

In Node.js we have direct access to global properties, without having to include it in the application.

Global objects and global variables

The most fundamental global role is as a global host variable. By ECMAScript definition, the following conditions are global variables:

  • The variable External is defined;
  • Global object properties;
  • The variable is implicitly defined (direct assignment to undefined variables).

When you define a global variable, the variable will also become the property of the global object, and vice versa. Note that, in Node.js, you cannot define variables in an external context, since all user code is part of the current module, and the module itself is not an external context.

Note: always use var to define variables in order to avoid introducing a global variable, as global variables will pollute the namespace, increasing the risk of communication code.

__filename

__filename specifies the file name of the script currently running. The absolute path to the location where the output file will be, but the command line option and specify the file name are not necessarily the same. If in a module, the returned value is the path to the module's file.

examples

// 输出全局变量 __filename 的值 console.log(__filename);

$ node main.js /web/com/w3big/nodejs/main.js

__dirname

__dirname represents the script directory currently located.

examples

Create a main.js file, code like this:

// 输出全局变量 __dirname 的值 console.log(__dirname);

The main.js executable file, the code looks like this:

$ node main.js /web/com/w3big/nodejs

setTimeout(CB, ms)

setTimeout(C - Bi, ms): The SetTimeout() function is specified only once.

It returns the value of the handle representing the timer.

examples

Create a main.js file, code like this:

Function printHello())( console.log("Hello, World!"); ) // setTimeout(printHello, 2000);

The main.js executable file, the code looks like this:

$ node main.js Hello, World!

clearTimeout(t)

clearTimeout(t) is used to stop the global function before passing setTimeout() to create the timer. Parameter T function setTimeout() to create a calculator.

examples

Create a main.js file, code like this:

Function printHello())( console.log("Hello, World!"); ) // var t = setTimeout(printHello, 2000); // 清除定时器 clearTimeout(t);

The main.js executable file, the code looks like this:

$nodemain.js

setInterval(CB, ms)

setInterval(C - Bi, ms) The global function executes the specified function after a specified number of milliseconds (ms) Number (CB).

It returns the value of the handle representing the timer. You can use the function clearInterval(T) to clear the timer.

The setInterval() method will continue to call the function until clearInterval() is called or the window is closed.

examples

Create a main.js file, code like this:

Function printHello())( console.log("Hello, World!"); ) // setInterval(printHello, 2000);

The main.js executable file, the code looks like this:

$ node main.js Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! ......

The above program will output "Hello, World!" once every two seconds, and will continuously execute until the button is pressed CTRL + C.

console

Console The console for providing standard output, which is the debugging facility provided by the JScript engine in Internet Explorer, and later became the de facto standard browser.

Node.js follows this standard, ensuring consistent behavior and habits of the console object used in the standard output stream (STDOUT) or standard error stream (STDERR) output characters.

console method

Below is the console object:

No.Method and description
1 console.log([data] [, ... ])
For standard printable output stream characters and end with a newline character. This method accepts several parameters, if there is only one parameter, then the output is a string of this parameter. If there are multiple arguments, places such as the command output format in C E().
2 console.info([data] [, ... ])
P role of the command returns an informational message, the console.log command does not make much difference, in addition to chrome, only text will be output, the rest will show a blue exclamation mark.
3 console.error([data] [, ... ])
Output error message. The console will display red when a fork error occurs.
4 console.warn([data] [, ... ])
A warning message is displayed. The console displays with a yellow exclamation mark.
5 console.dir(OBJ[, options])
Object used for inspection (inspection) and easy to read display and print formats.
6 console.time (shortcut)
Time output, start time.
7 console.timeEnd(shortcut)
End time, which indicates the end of time.
8 console.trace(message [, ...])
The code currently implements the call path on the stack, running this test function is useful, just want to test the function which is joined by console.trace on the line.
9 console.assert(value[, message][, ...])
To determine whether a variable or expression is true, two parameters were required, the first parameter is an expression and the second argument is a string. Only when the first argument is false, then the output will be the second argument; it will have no results.
console.log(): Print to standard output and end with a newline.

console.log accepts multiple parameters, if there is only one parameter, the output string of that parameter. If there are multiple arguments, places such as the command output format in C E().

The first parameter is a string, no parameters, just print a newline character.

Console.log("Hello world"); console.log("byvoid%diovyb"); console.log("byvoid%diovyb", 1991);

Hello world byvoid%diovyb byvoid1991iovyb

  • console.error(): With console.log() it does the same thing, but outputs to standard error.
  • console.trace(): Stream errors to standard output of the current call stack.
console.trace();

Operating results as follows:

Trace: at Object. (/home/byvoid/consoletrace.js:1:71) at Module._compile (module.js:441:26) at Object..js (module.js:459:10) at Module.load (module.js: 348:31) at Function._load (module.js:308:12) at Array.0 (module.js:479:10) at EventEmitter._tickCallback (node.js:192:40)

examples

Create a main.js file, code like this:

Console.info("程序开始执行:"); var counter = 10; console.log("计数: %d", counter); console.time("获取数据"); // // 执行一些代码 // console.timeEnd("获取数据"); console.info("程序执行完毕。")

The main.js executable file, the code looks like this:

$ node main.js 程序开始执行:计数: 10获取数据: 0ms 程序执行完毕

process

A process is a global variable, an attribute is a global object.

It is used to describe the current process state of a Node.js object and provides a simple interface to the operating system. Usually you write your own command line programs and end up dealing with it. Below will introduce some of the most commonly used method of objecting process by members.

No.Events and description
1 exit
Fires when the process is ready to quit.
2 beforeExit
This event is fired when the node has an empty event loop, and no other action is taken. In general, there is no process to organize an exit node, but "beforeExit" listeners can be called asynchronously so that the node will continue.
3 uncaughtException
When an exception is boiled back into the event loop, raise this event. If you add a monitor to an exception, the default action (stack printing and exit) will not occur.
4 The signal is triggered when
event when the process receives a signal.
Review the list of standard POSIX signal names such as SIGINT, SIGUSR1, and so on.

examples

Create a main.js file, code like this:

Process.on("exit", function(code) ( // setTimeout(function() ( console.log("该代码不会执行"); 0); console.log(" 退出码为:", code); )); console.log("程序执行结束");

The main.js executable file, the code looks like this:

$ node main.js 程序执行结束退出码为: 0

Output Status Codes

The exit status codes are as follows:

Status codeTitle and description
1 Uncaught Fatal Exception
There is an uncaught exception and it was not handled or the domain of the uncaughtException handler.
2 unused
retention
3 JavaScript Internal Error Analyze
The JavaScript error parsing source code is called when the Node process starts. Very rarely, only when Node.
4 Internal JavaScript fault Score
The JavaScript process running the source node returns failure when evaluating the function. Very rarely, only when Node.
5 Fatal error
V8 in an uncorrectable error with a fatal outcome. Usually print Stderr, content: fatal error
6 Non-Function Internal Exception Handler
Uncaught exception, the exception handler inside is somehow set to the function, and also cannot be called.
7 Internal Run-Time Handler Exception Failure
Uncaught exception, and the exception handler to handle its own throws an exception. For example, if process.on("uncaughtException") or domain.on("error") throws an exception.
8 unused
retention
9 Invalid argument
It may be unknown parameters or parameter to value.
10 Internal JavaScript Run-Time failed
JavaScript source code is generated when errors are triggered in the Node process, very rarely, only when there is development of Node.
12 Invalid Debug Argument
--debug option set and/or --debug-BRK, but selected the wrong port.
> 128 Signal outputs
If a node receives a fatal signal, such as SIGKILL or SIGHUP, then the return code is 128 plus the signal code. This is standard Unix practice, high code on the output signals.

process attributes

The process provides many useful properties, ease of interaction, that we can better control the system:

Qty.Property & Description
1 STDOUT
Standard output stream.
2 STDERR
Standard error stream.
3 STDIN
Standard input stream.
4 ARGV
The ARGV property returns an array of various options for executing a command line script when composing. Its first members are always a node, its second member is the script file name, and the remaining members are script file parameters.
5 execPath
Returns the absolute path of the current script execution binary node.
6 execArgv
Returns the array member located under the command line script executed between the node executable command line parameters of the script file.
7 ENV
Returns an object, the members of the current shell environment variable
8 ExitCode
The exit code for the process, if the process is presented with process.exit() exit, without specifying an exit code.
9 version
node version, such as v0.10.18.
10 versions
A property that contains the versions of nodes and dependencies.
11 config
The object that contains the current node is used to compile the executable javascript options configuration file. This is the same run./configure script created by the "config.gypi" file.
12 PID - regulator
Current process number.
13 Name
Process name, default "node", you can customize the value.
14 arch
Current CPU architecture: "arm", "ia32" or "64".
15 platform
Run the program where the platform is "Darwin", "FreeBSD", "Linux", "SunOS" or "win32"
16 mainModule
require.main alternative methods. Various points, if the main module changes at runtime, require.main may keep falling back to the old module. Both are considered to belong to the same module.

examples

Create a main.js file, code like this:

// 输出到终端 process.stdout.write("Hello World!" + "\n"); // 通过参数读取 process.argv.forEach(function(val, index, array) ( console.log(index + ": " + val); )); // 获取执行路局 console.log(process.execPath); // 平台信息 console.log(process.platform);

The main.js executable file, the code looks like this:

$ node main.js Hello World! 0: node 1: /web/www/node/main.js /usr/local/node/0.10.36/bin/node darwin

Method Reference Guide

The process provides many useful methods to facilitate more efficient control of our interactive system:

No.Method and description
1 abort()
This will raise the interrupt node trigger event. This will cause node to exit and create a dump file.
2 ChDir (directory)
Change the process's current working directory if the operation cannot quit.
3 EAR ()
Returns the working directory of the current process
4 exit([code])
Ends the process with the specified code. If this parameter is omitted, it will use code 0.
5 getgid()
Get process group identification (see getgid(2)). When a group was purchased a digital ID rather than a name.
6 setgid(ID)
Setting up the group identification process (see setgid (2)). The ID can take a numeric or group name. If you specify a group name, blocking will be allowed waiting for a digital ID.
Note: This function can only be used (eg non-Windows and Android) on POSIX platforms.
7 getuid()
Get the user's identification process (see getuid(2)). This is a numeric user ID, not a user name.
Note: This function can only be used (eg non-Windows and Android) on POSIX platforms.
8 UIP (ID)
Process setup user ID (see UIP (2)). Retrieving a digital identifier or name string. If you specify a group name, blocking will be allowed waiting for a digital ID.
Note: This function can only be used (eg non-Windows and Android) on POSIX platforms.
9 getgroups()
The process of returning the group ID array. The POSIX system does not guarantee that it is, but Node.js is guaranteed to be there.
Note: This function can only be used (eg non-Windows and Android) on POSIX platforms.
10 setgroups
Set the process group ID. It is eligible to work, all you need is to have superuser privileges, or have the CAP_SETGID capability.
Note: This function can only be used (eg non-Windows and Android) on POSIX platforms.
11 initgroups(user, extra_group)
Reading / etc. /group, and initializes the group access list, all members of the group are located. It is eligible to work, all you need is to have superuser privileges, or have the CAP_SETGID capability.
Note: This function can only be used (eg non-Windows and Android) on POSIX platforms.
12 kill (IDP [signal])
Sends a signal to a process. The ID is the process identifier, and the signal is a string indicating the signal being transmitted. Signal names are strings like "SIGINT" or "" SIGHUP. If this parameter is omitted, the signal will be "SIGTERM".
13 MemoryUsage()
It returns an object that describes the process used by the node's memory status bytes.
14 nextTick(callback)
After the current function callback event loop ends.
15 Umask ([mask])
Set or read process mask file. Child processes inherit this mask from the parent process. If the mask argument is true, then it returns the old mask. Otherwise, it returns the current mask.
16 Spent()
Returns the number of seconds Node has already started.
17 hrtime()
Time resolution of the current process, specified as [seconds] array nanoseconds. This is relative to any past event. This value has nothing to do with the date, so it does not affect clock drift. The main purpose is over a precise period of time to measure the performance of the program.
Before the result can be passed to the current process.hrtime(), it will return the time difference between them, for the reference and time interval measurement.

examples

Create a main.js file, code like this:

// 输出当前目录 console.log("当前目录: " + process.cwd()); // 输出当前版本 console.log("当前版本: " + process.version); // 输出内存使用情况 console.log(process.memoryUsage());

NODE.JS– a software tool for executing js.

Nodejs = V8 + I/O + libraries

V8: fast, modern, economical

Advantages

  • Javascript
  • Common code on client and server
  • Basic web tasks
  • Many connections and tasks at the same time
  • Easy to create a working prototype
  • Convenient npm package manager
  • Community

Installation

When installing, nodejs writes itself to the PATH variable (+ npm), [administration - environment variables]; can be checked on the command line:
set PATH

As a rule, files are launched under nodejs: let's write a simple script and run it via the command line:


The script will be executed and the result will be displayed on the command line.

Nodejs documentation

nodejs modules

To understand how the built-in nodejs modules work, you need to download the source code archive from the nodejs website (source code). And go to the lib directory. (dir command - get a list of files via the command line; If you need to list files in all subfolders, then instead of "dir" use "dir /s"). If you installed nodejs from a package, you will not find any files in the lib folder.

Nodejs has modules with varying degrees of stability. (for example, 0 – should not be used; 1, 2 – can be used but the module API may change).

The functions are growing (the project is developing) and over time we will need to move the USER constructor function into a separate file. This is where modules come into play.

Modules are a kind of way that nodejs offers to organize a project.

Projects tend to grow, which leads to the desire to split the project into several files - this is where modules come into play.

require

For HTML pages, script tags are used to include scripts. Nodejs has a special require command.

Var user = require("./user");

In our example, we access the file (user.js) in the same directory (the extension (.js) is optional).

//require("./user"); // .js is not necessary to specify // in this case the file will be executed, but there will be no USER variable // this is the main difference from script tags from nodejs // In node.js, the functions and variables of each module are global // for this file (the module itself) and they do not automatically // become available when connected (require("./user")) // But how to gain access? // Each module has a special variable exports - this is an object and what // I put there will return as a result require var user = require("./user.js"); // result: user = ( User: function )

The first difference between the nodejs modular system and browser scripts: if there are two script tags in the browser, then a function that is defined at the global level in one of them is available in the other, but not in nodejs. In nodejs, functions and variables are global for a given file (they are not available when required). Thus, nodejs allows you to write truly independent modules. But for the module to be available, it is used export system. Each module has a special exports variable.

Module-directory DIR/index

We connect the folder directly var user = require("./user"); , which contains the corresponding index.js .

For example

Function User(name)( this.name = name; ) User.prototype.hello = function(who)( console.log(phrases.Hello + ", " + who.name); ); exports.User = User;

We connect and use the User constructor in the file ./server.js

//server.js var user = require("./user"); var vasya = new user.User("Vasya");

"./" - relative to the current folder

exports is an object and what is put there will be returned as the result of require (exports.jpg). This way the module can declare its private variables/functions and export only what is needed.


For global variables, etc. there is a global object

Global.User = User;

Bottom line

  • Connection require
  • Variables: var (private for modules), exports, global (rarely used)
  • Types of modules: js, node (with the .node extension), json (with the .json extension). Json modules are used when you need to store some simple information on a file.
  • Module-directory DIR/index

module object

  • module object
  • Module-function module.exports = function
  • Caching modules (the module is never read again)
  • Module arrangement: search order
  • Passing parameters: module-factory

The module object (the fundamental object for modules) is a variable that exists in each module (file, you can output console.log(module;);). . Contents: id property – usually the path to the file,
parent – ​​link to the parent module (module.parent – ​​link to the parent module that requires this),
children (module.children - those modules that are connected via require),
exports property and others.

Module or application? module.parent

The module can be launched directly, but if not, if the functionality is connected to another module, then let it export this functionality. These two cases can be separated by checking:

If(module.parent) ( exports.run = run; ) else ( run(); )


ps: as they say on stackoverflow.com The parent is the module that called the script for interpretation

// $ node foo.js console.log(module.parent); // null // require("./foo") console.log(module.parent); // ( ... )

Proper use of module.exports

In the context of a module:

module.exports = exports = this (these constructs are equivalent)

If you want to pass a function not in an object, but directly, then use the following syntax:

Module.exports = User;


Module caching

When Nodejs loads a module, it completely creates the corresponding module object (taking into account parent , exports and other similar properties) and remembers it in itself (module.id (the full path to the file) serves as an identifier for the internal cache) and the next time we re- we access (connect) to any module (file), nodejs takes the same object from the cache. That is, for example, it is enough to initialize a module once in a file; in the future you can simply use it.

In our case, for var db = require("../db");
and for var db = require("./db"); the same object is taken. Therefore, the principle is as follows: the first time a module is used, it is initialized and in the future we only connect it and use it (that is, in our case we do not need to use db.connect() twice, that is, in different files).


Module arrangement: the order in which modules are found in nodejs

How to make the db always connect without specifying a specific path:

Var db = require("../db"); //or var db = require("./db");

and like this:

Var db = require("db");

regardless of the file in which db is connected.

To do this, you need to understand the search order for modules in nodejs (what happens when require is called). There are many built-in modules in nodejs, for example require("fs"); , which will be connected without problems. If you specify a specific path in require, for example, require("../db"); , then the search will be based on the given path and the file will be found, or nodejs will try to get this file as a directory (and will look for index.js inside the category).

If you specify require("db"); and the module is not built-in, then the node_modules directory will be searched relative to the current position (if found, it will try to take the module from it). If the node_modules directory is missing, then the node_modules directory will be searched above, etc.

Besides specifying a specific path for a module, nodejs can search for modules like this:

Introduction to npm - the package manager for Node.JS

  1. create a package description file (package.json) that contains information about the module (name, version, etc.). Either manually or via command
    npm init
    (will ask for the necessary information)
  2. To publish a module you need to:
    1. Add a user using the npm adduser command (you must enter Username and Password). Now all work with npm will be done on behalf of this user. The user can log in to https://www.npmjs.com/~name_user and monitor their modules.
    2. Publishing: npm publish
  3. Then someone can use your module added to the database, and the user himself can make changes.
  4. Get all npm commands using the npm help command
  5. Search for a module in the database: npm s keywords or npm search keywords (for example, npm s super module)
  6. Install the module: npm install name_module or npm i name_module
  7. When installing modules, nodejs first looks for the node_modules folder in the current directory (then higher and higher, etc.), or (if node_modules is missing) looks for package.json (also going up; package.json usually denotes the root of the project) and, accordingly, if it finds package.json, it creates a node_modules folder in the corresponding directory; if both options fail, then nodejs creates a node_modules folder in the current directory. If you want to place a module in a specific directory, then you need to create a node_modules folder in that directory.
  8. npm up update module (will check for update modules that are in the node_modules folder)
  9. npm remove modulename (remove module)

Output from npm:

npm init
nmp adduser
npm publish
npm search keywords
npm install module
npm update module
npm remove module
npm help command

NPM Package Structure

Installing the required version, for example: npm i [email protected]

The latest version of the module can be obtained if the module is developed using the git versioning system, for example, on github. It is enough to get Git Read-Only (url): https://github.com/strongloop/express.git and in the console:

npm i https://github.com/strongloop/express.git

dependencies in package.json

dependencies points to those modules on which this one depends.

devDependencies

Modules registered in devDependencies are not installed if the module is pulled as a dependency. They are installed only for development and can be installed if, for example, you go to the module in the node_modules folder and enter npm i (or by setting the npm config flag).

the main field specifies the entry point into the package

Global modules

Any module can be installed globally if you set the -g flag: npm -g module

Global means to the system directory.

Directory of global modules for windows:

C:\users\User_Name\AppData\Roaming\npm

Global modules are placed in the standard system directory. Those binaries that are in package.json will be installed on the system path (this is the main use of global modules), that is, in the future they can be called through the console.

Based on materials from I. Kantor's courses

In a node, you can set global variables via a "global" or "GLOBAL" object:

GLOBAL._ = require("underscore"); // but you "shouldn"t" do this! (see note below)

or more useful...

GLOBAL.window = GLOBAL; // like in the browser

From the node source you can see that they are aliases to each other:

Node-v0.6.6/src/node.js:28:global = this; 128: global.GLOBAL = global;

In the above code, "this" is the global context. With the commonJS module (which node uses), this "object" inside the module (i.e. "your code") is NOT the global context. For proof of this, see below where I spew out "this" object and then the giant "GLOBAL" object.

Console.log("\nTHIS:"); console.log(this); console.log("\nGLOBAL:"); console.log(global); /* outputs ... THIS: {} GLOBAL: ( ArrayBuffer: , Int8Array: ( BYTES_PER_ELEMENT: 1 ), Uint8Array: ( BYTES_PER_ELEMENT: 1 ), Int16Array: ( BYTES_PER_ELEMENT: 2 ), Uint16Array: ( BYTES_PER_ELEMENT: 2 ), Int32Array: ( BYTES_PER_ELEMENT: 4 ), Uint32Array: ( BYTES_PER _ELEMENT: 4 ), Float32Array: ( BYTES_PER_ELEMENT: 4 ), Float64Array: ( BYTES_PER_ELEMENT: 8 ), DataView: , global: , process: ( EventEmitter: , title: "node", assert: , version: "v0.6.5", _tickCallback: , moduleLoadList: [ "Binding evals", "Binding natives", "NativeModule events", "NativeModule buffer", "Binding buffer", "NativeModule assert", "NativeModule util", "NativeModule path", "NativeModule module", "NativeModule fs", "Binding fs", "Binding constants", "NativeModule stream", "NativeModule console", "Binding tty_wrap", "NativeModule tty", "NativeModule net", "NativeModule timers", "Binding timer_wrap", "NativeModule _linklist" ], versions: ( node: "0.6.5", v8: "3.6.6.11", ares: "1.7.5-DEV", uv: "0.6", openssl: "0.9.8n" ), nextTick: , stdout: , arch: "x64", stderr: , platform: "darwin", argv: [ "node", "/workspace/zd/zgap/darwin-js/index.js" ], stdin: , env: ( TERM_PROGRAM: "iTerm.app", "COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET": "/tmp/launch-nNl1vo/ServiceProcessSocket", TERM: "xterm", SHELL: "/bin/bash", TMPDIR: "/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/", Apple_PubSub_Socket_Render: "/tmp/launch-9Ga0PT/Render", USER: "ddopson", COMMAND_MODE: "unix2003", SSH_AUTH_SOCK: "/tmp/launch -sD905b/Listeners", __CF_USER_TEXT_ENCODING: "0x12D732E7:0:0", PATH: "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11 /bin", PWD: "/workspace/zd/zgap/darwin-js", LANG: "en_US.UTF-8", ITERM_PROFILE: "Default", SHLVL: "1", COLORFGBG: "7;0", HOME : "/Users/ddopson", ITERM_SESSION_ID: "w0t0p0", LOGNAME: "ddopson", DISPLAY: "/tmp/launch-l9RQXI/org.x:0", OLDPWD: "/workspace/zd/zgap/darwin-js /external", _: "./index.js"), openStdin: , exit: , pid: 10321, features: ( debug: false, uv: true, ipv6: true, tls_npn: false, tls_sni: true, tls: true ), kill: , execPath: "/usr/local/bin/node", addListener: , _needTickCallback: , on: , removeListener: , reallyExit: , chdir: , debug: , error: , cwd: , watchFile: , umask : , getuid: , unwatchFile: , mixin: , setuid: , setgid: , createChildProcess: , getgid: , inherits: , _kill: , _byteLength: , mainModule: ( id: ". ", exports: (), parent: null, filename: "/workspace/zd/zgap/darwin-js/index.js", loaded: false, exited: false, children: , paths: ), _debugProcess: , dlopen: , uptime: , memoryUsage: , uvCounters: , binding: ), GLOBAL: , root: , Buffer: ( poolSize: 8192, isBuffer: , byteLength: , _charsWritten: 8 ), setTimeout: , setInterval: , clearTimeout: , clearInterval: , console: , window: , navigator: () ) */

**Note: Regarding setting "GLOBAL._", in general you should just do var _ = require("underscore"); Yes, you do this in every file that uses the underscore, just like in Java you import com.foo.bar; This makes it easier to determine what your code is doing because the links between files are "explicit". Mildly annoying, but good. This is a sermon.

There is an exception to every rule. I had exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "config" files that were mostly JSON, but were "written in JS" to add a little more flexibility. There were no "require" statements in such config files, but I wanted them to have access to underscore (the ENTIRE system was based on underscore and underscore patterns), so I would set "GLOBAL._" before evaluating "config". So yes, for every rule there is an exception somewhere. But you have a good reason, not just "I'm tired of typing" so I want to break the agreement."

and I was told that I could set the variables to the global scope, leaving var.

This doesn't work for me.

Require("underscore");

Does not make _ available for required files. I can install app.set and use it elsewhere.

Can anyone confirm that this should work? Thank you.

In node you can set global variables via the "global" or "GLOBAL" object:

GLOBAL._ = require("underscore"); // but you "shouldn"t" do this! (see note below)

or more useful...

GLOBAL.window = GLOBAL; // like in the browser

From the node source you can see that they are aliases to each other:

Node-v0.6.6/src/node.js:28:global = this; 128: global.GLOBAL = global;

In the above code, "this" uses the global context. In the commonJS modular system (which node uses), the "this" object inside the module (i.e. "Your Code") is NOT the global context. For proof of this, see below where I invert a "this" object and then a giant "GLOBAL" object.

Console.log("\nTHIS:"); console.log(this); console.log("\nGLOBAL:"); console.log(global); /* outputs ... THIS: {} GLOBAL: ( ArrayBuffer: , Int8Array: ( BYTES_PER_ELEMENT: 1 ), Uint8Array: ( BYTES_PER_ELEMENT: 1 ), Int16Array: ( BYTES_PER_ELEMENT: 2 ), Uint16Array: ( BYTES_PER_ELEMENT: 2 ), Int32Array: ( BYTES_PER_ELEMENT: 4 ), Uint32Array: ( BYTES_PER _ELEMENT: 4 ), Float32Array: ( BYTES_PER_ELEMENT: 4 ), Float64Array: ( BYTES_PER_ELEMENT: 8 ), DataView: , global: , process: ( EventEmitter: , title: "node", assert: , version: "v0.6.5", _tickCallback: , moduleLoadList: [ "Binding evals", "Binding natives", "NativeModule events", "NativeModule buffer", "Binding buffer", "NativeModule assert", "NativeModule util", "NativeModule path", "NativeModule module", "NativeModule fs", "Binding fs", "Binding constants", "NativeModule stream", "NativeModule console", "Binding tty_wrap", "NativeModule tty", "NativeModule net", "NativeModule timers", "Binding timer_wrap", "NativeModule _linklist" ], versions: ( node: "0.6.5", v8: "3.6.6.11", ares: "1.7.5-DEV", uv: "0.6", openssl: "0.9.8n" ), nextTick: , stdout: , arch: "x64", stderr: , platform: "darwin", argv: [ "node", "/workspace/zd/zgap/darwin-js/index.js" ], stdin: , env: ( TERM_PROGRAM: "iTerm.app", "COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET": "/tmp/launch-nNl1vo/ServiceProcessSocket", TERM: "xterm", SHELL: "/bin/bash", TMPDIR: "/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/", Apple_PubSub_Socket_Render: "/tmp/launch-9Ga0PT/Render", USER: "ddopson", COMMAND_MODE: "unix2003", SSH_AUTH_SOCK: "/tmp/launch -sD905b/Listeners", __CF_USER_TEXT_ENCODING: "0x12D732E7:0:0", PATH: "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11 /bin", PWD: "/workspace/zd/zgap/darwin-js", LANG: "en_US.UTF-8", ITERM_PROFILE: "Default", SHLVL: "1", COLORFGBG: "7;0", HOME : "/Users/ddopson", ITERM_SESSION_ID: "w0t0p0", LOGNAME: "ddopson", DISPLAY: "/tmp/launch-l9RQXI/org.x:0", OLDPWD: "/workspace/zd/zgap/darwin-js /external", _: "./index.js"), openStdin: , exit: , pid: 10321, features: ( debug: false, uv: true, ipv6: true, tls_npn: false, tls_sni: true, tls: true ), kill: , execPath: "/usr/local/bin/node", addListener: , _needTickCallback: , on: , removeListener: , reallyExit: , chdir: , debug: , error: , cwd: , watchFile: , umask : , getuid: , unwatchFile: , mixin: , setuid: , setgid: , createChildProcess: , getgid: , inherits: , _kill: , _byteLength: , mainModule: ( id: ". ", exports: (), parent: null, filename: "/workspace/zd/zgap/darwin-js/index.js", loaded: false, exited: false, children: , paths: ), _debugProcess: , dlopen: , uptime: , memoryUsage: , uvCounters: , binding: ), GLOBAL: , root: , Buffer: ( poolSize: 8192, isBuffer: , byteLength: , _charsWritten: 8 ), setTimeout: , setInterval: , clearTimeout: , clearInterval: , console: , window: , navigator: () ) */

**Note: Regarding setting "GLOBAL._" , in general you should just do var _ = require("underscore"); . Yes, you do this in every file that uses underscore, just like in Java you do import com.foo.bar; . This makes it easier to determine what your code is doing because the links between files are "explicit". Mildly annoying, but good..... It's preachy.

There is an exception to every rule. I had exactly one instance where I needed to set "GLOBAL._" . I was creating a system for defining "config" files that were mostly JSON, but were "written in JS" to add a little more flexibility. There were no "require" statements in such config files, but I wanted them to have access to underscore (the ENTIRE system was based on underscore and underscore patterns), so I would set "GLOBAL._" before evaluating "config". So yes, for every rule there is an exception somewhere. But you have a good reason, not just "I'm tired of typing the 'require' so I want to break the agreement."