C:\temp>node
> console.log("Hello Node!");
Hello Node!
test.js
C:\temp>node test.js Hello Node!
module.exports object that is used to expose
objects
// hello.js
var sayHello = function() {
return 'Hello Node';
};
// Export object "hello" that is
// the same as sayHello()
module.exports.hello = sayHello;
require() imports objects from module.exports
// Search for hello.js in the same directory
var imported = require('./hello.js');
console.log(imported.hello()); // Hello Node
// config.js
var config = {
maxUnits: 100
};
module.exports = config;
Get access to config's variables:
// server.js
var config = require('./config.js');
console.log(config.maxUnits); // 100
npm command-line tool to download and install
(Alt-F12 in WebStorm)
mkdirp package
$gt; npm install mkdirp
require function to load the module
// Search for node_modules/mkdirp.js or
// node_modules/mkdirp/index.js
var mkdirp = require('mkdirp');
// Create temp dir
mkdirp('temp', function(err) {
if (err)
console.log(err);
else
console.log("dir was created");
});
package.json
package.json:
{
"name": "mkdirp",
"description": "Recursively mkdir, like `mkdir -p`",
"version": "0.5.0",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
etc...
}
// server.js
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello, Node!');
response.end();
});
server.listen(4000);
console.log("Server is listening on port 4000");
server.js and access URL in web browser
http://localhost:4000/