Knowledge.ToString()

How to Use Plain Old JavaScript File into Node.js as a Module

If you want to use your plain old JavaScript file into Node.js, you need to create a module which is nothing but a fancy wrapper around your JavaScript file and then you can use all the functions of your JavaScript object into Node.js.

Environment

  • Windows 7 (64 bit)
  • Node.js 4.4.2 (64 bit)
  • Path already contains node executable so when you open up command prompt and type “node” and hit Enter key, it will be ready to accept node commands.
  • BASE_DIR = “C:\temp\nodejs\”. This is where I have my source code stored.

File/folder structure

  • BASE_DIR/app.js
  • BASE_DIR/node_modules/helloworld/index.js
  • BASE_DIR/node_modules/helloworld/lib/helloworld.js

Download Source Code

helloworld.js code

function HelloWorld() {
	this.sayHello = function ()
	{
		return "Hello. Current time = " + Date();
	}
};

index.js code

var fs = require('fs');
 
// Read and eval library
filedata = fs.readFileSync('./node_modules/helloworld/lib/helloworld.js','utf8');
eval(filedata);
 
exports.HelloWorld = HelloWorld;

app.js code

//Import helloworld module
var hello = require('helloworld');
 
// Create an object
var hw = new hello.HelloWorld();
 
// Execute object method
console.log(hw.sayHello());

How to execute?

  1. Open Windows Explorer and navigate to BASE_DIR.
  2. Press Shift key and right click on the Windows Explorer in open space and then click on “Open command prompt here” to open up command prompt
  3. Type “node app.js” and it will execute the JavaScript file and show the message with current date and time

Share

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *