Running JavaScript Programs
For a console like JavaScript shell type node
in a windows, Mac, or Linux command window. Use .exit
to exit.
To run a JavaScript file type node Filename.js
from a command shell.
Example
File hiNode.js, run with node hiNode.js
// File: hiNode.js
let a = [1, 3, 5, 7, 9, 11];
function cube(x) {
return x*x*x;
}
console.log("Hello from Node.js");
for (let x of a) {
console.log(`x = ${x} and x cubed = ${cube(x)}`);
}
Node.js API Use
Node.js now supports ES6 modules
- Use ES6
import
syntax
- Use ES6
export
syntax
- Don’t need paths for either built in modules or those install with NPM
Example: Filesystem Access
Getting a list of all files in a directory fileList.mjs
// List all the files in the current directory
// ES6 module syntax
import fs from 'fs'; // File system module
let allFiles = fs.readdirSync(".");
console.log("Files in the current directory: ");
allFiles.forEach(function(f) { console.log('\t' + f); });
Synchronous File Read
Simple File Reading syncRead.mjs
// Simple Synchronous file reading
// Using ES6 Modules.
import fs from 'fs'; // File system module
let fname = './whoAmI.js';
let fdata = fs.readFileSync(fname, 'utf8');
console.log("Contents of file whoAmI.js:");
console.log(fdata);
Synchronous File Write
File syncWrite.mjs
// Simple Synchronous file Write
// ES6 modules
import fs from 'fs'; // File system module
let fname = './tempWrite.txt';
let data = "Just a little text. \n Did this write?";
let fdata = fs.writeFileSync(fname, data);
console.log("Wrote test file: tempWrite.txt");
Network Access
Getting information about network interfaces netIf.mjs
// A simple program to look at IPv4 addresses
// for network interface via Node.js and ES6 modules
import os from 'os';
let networkInterfaces = os.networkInterfaces();
// console.log(networkInterfaces); // Shows everything
for (let intf in networkInterfaces) {
console.log(intf);
// Only interested in IPv4 interfaces
let addresses = networkInterfaces[intf]
.filter(a => a.family === 'IPv4');
console.log(addresses);
}
JSON Read/Parse
Read and Parse JSON quickJSON.mjs
// JSON reading and parsing with Node.js ES6 modules
import { readFile } from 'fs/promises'; // promise based file reading
const clubEvents = JSON.parse(await readFile(new URL('./eventData.json',
import.meta.url))); // URL for relative file location, regular JSON parsing
clubEvents.forEach(function(event) { //Look at data
console.log(event);
});
Node and CommonJS Modules
Useful Global Stuff
In the Globals section of the API documents you will find
- Important file related variables:
_dirname
, _filename
CommonJS only
- Import module function:
require()
CommonJS only
- The
console
for simple output and debugging always available
Node Knows about files/dirs’
When running a JavaScript file Node under CommonJS provides some global variables:
__filename
the full file name of this JavaScript file
__dirname
the directory this file is in
Example file and dir name
The following program is from the file whoAmI.js and is run with node whoAmI.js
.
console.log("Hello from Node.js");
console.log("The name of this file is: " + __filename);
console.log("This file is in the directory: " + __dirname);
Node.js CommonJS API Use
Node.js has a module system that predates the ES6 standard
- To “import” an API module for use syntax such as:
const varName = require('moduleName');
- Where varName is just the name of a variable that you choose and moduleName is the name of the API module.
Example: CommonJS Filesystem Access
Getting a list of all files in a directory fileList.js
// List all the files in the current directory
const fs = require('fs'); // Import file system module
let allFiles = fs.readdirSync(__dirname);
console.log("Files in the current directory: " + __dirname);
allFiles.forEach(function(f){console.log('\t' + f);});
CommonJS Synchronous File Read
Simple File Reading syncRead.js
// syncRead.js
const fs = require('fs'); // File system module
let fname = __dirname + '/whoAmI.js';
let fdata = fs.readFileSync(fname, 'utf8');
console.log("Contents of file whoAmI.js:");
console.log(fdata);
CommonJS Synchronous File Write
File syncWrite.js
// syncWrite.js
const fs = require('fs'); // File system module
let fname = __dirname + '/tempWrite.txt';
let data = "Just a little text. \n Did this write?";
let fdata = fs.writeFileSync(fname, data);
console.log("Wrote test file: tempWrite.txt");
CommonJS Network Access
Getting information about network interfaces netIf.js
// netIf.js
// Let's look at your machines IPv4 addresses
const os=require('os');
let networkInterfaces = os.networkInterfaces();
// console.log(networkInterfaces); // Shows everything
for (let intf in networkInterfaces){
console.log(intf);
// Only interested in IPv4 interfaces
let addresses = networkInterfaces[intf]
.filter(a => a.family === 'IPv4');
console.log(addresses);
}