Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Require()

Other topics

Remarks:

Using require() allows code to be structured in a way similar to Java's use of classes and public methods. If a function is .export'ed, it can be require'ed in another file to be used. If a file is not .export'ed, it cannot be used in another file.

Beginning require() use with a function and file

Require is a statement that Node interprets as, in some sense, a getter function. For example, say you have a file named analysis.js, and the inside of your file looks like this,

function analyzeWeather(weather_data) {
  console.log('Weather information for ' + weather_data.time + ': ');
  console.log('Rainfall: ' + weather_data.precip);
  console.log('Temperature: ' + weather_data.temp);
  //More weather_data analysis/printing...
}

This file contains only the method, analyzeWeather(weather_data). If we want to use this function, it must be either used inside of this file, or copied to the file it wants to be used by. However, Node has included a very useful tool to help with code and file organization, which is modules.

In order to utilize our function, we must first export the function through a statement at the beginning. Our new file looks like this,

module.exports = {
  analyzeWeather: analyzeWeather
}
function analyzeWeather(weather_data) {
  console.log('Weather information for ' + weather_data.time + ': ');
  console.log('Rainfall: ' + weather_data.precip);
  console.log('Temperature: ' + weather_data.temp);
  //More weather_data analysis/printing...
}

With this small module.exports statement, our function is now ready for use outside of the file. All that is left to do is to use require().

When require'ing a function or file, the syntax is very similar. It is usually done at the beginning of the file and set to var's or const's for use throughout the file. For example, we have another file (on the same level as analyze.js named handleWeather.js that looks like this,

const analysis = require('./analysis.js');

weather_data = {
  time: '01/01/2001',
  precip: 0.75,
  temp: 78,
  //More weather data...
};
analysis.analyzeWeather(weather_data);

In this file, we are using require() to grab our analysis.js file. When used, we just call the variable or constant assigned to this require and use whatever function inside that is exported.

Beginning require() use with an NPM package

Node's require is also very helpful when used in tandem with an NPM package. Say, for example, you would like to use the NPM package require in a file named getWeather.js. After NPM installing your package through your command line (git install request), you are ready to use it. Your getWeather.js file might like look this,

var https = require('request');

//Construct your url variable...
https.get(url, function(error, response, body) {
  if (error) {
    console.log(error);
  } else {
    console.log('Response => ' + response);
    console.log('Body => ' + body);
  }
});

When this file is run, it first require's (imports) the package you just installed called request. Inside of the request file, there are many functions you now have access to, one of which is called get. In the next couple lines, the function is used in order to make an HTTP GET request.

Syntax:

  • module.exports = {testFunction: testFunction};
  • var test_file = require('./testFile.js'); //Let us have a file named testFile
  • test_file.testFunction(our_data); //Let testFile have function testFunction

Contributors

Topic Id: 10742

Example Ids: 32228,32229

This site is not affiliated with any of the contributors.