I/O

  • Path
  • require
  • export
  • File system

path

path.basename

path.basename returns last portion of path.

path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'
path.dirname(path)

path.dirname(path)

path.resolve(path)
path.resolve(path);

Require

What happens when you require module.

  1. Resolve path to the module.
  2. Check Module._cache for the cached module.
  3. If cache is empty, create a new Module instance and store it to the cache.
  4. Call module.load()with the given filename.
  5. Invoke module.compile() after reading the file contents. If there was an error loading/parsing the file, delete the bad module from cache.
  6. wrapping it in private scope.
  7. return module.export

require.main

require.main

/*
Module {
  id: '.',
  exports: {},
  parent: null,
  filename: '/Users/kei/Dev/exp/node/module.js',
  loaded: false,
  children: [],
  paths:
   [ '/Users/kei/Dev/exp/node/node_modules',
     '/Users/kei/Dev/exp/node_modules',
     '/Users/kei/Dev/node_modules',
     '/Users/kei/node_modules',
     '/Users/node_modules',
     '/node_modules' ] }
*/

require.resolve

require.resolve method does not load the file but just check if it exists.

require.resolve

require.cache

require.cache returns cache information

require.cache

/*
{ '/Users/kei/Dev/exp/node/fs.js':
   Module {
     id: '.',
     exports: {},
     parent: null,
     filename: '/Users/kei/Dev/exp/node/fs.js',
     loaded: false,
     children: [],
     paths:
      [ '/Users/kei/Dev/exp/node/node_modules',
        '/Users/kei/Dev/exp/node_modules',
        '/Users/kei/Dev/node_modules',
        '/Users/kei/node_modules',
        '/Users/node_modules',
        '/node_modules' ] } }
  */

require.extensions

require.extensions returns an object contains file extentions which automatically is resolved by node.js. Each property has function that handle files as value. For example, .js returns a function that compile file and `.json` return one that parse JSON.

require.extensions

// { '.js': [Function], '.json': [Function], '.node': [Function] }

require.extensions['.js'].toString()

/*
function (module, filename) {
  var content = fs.readFileSync(filename, 'utf8');
  module._compile(internalModule.stripBOM(content), filename);
}
*/

require.extensions['.json'].toString()

/*
function (module, filename) {
  var content = fs.readFileSync(filename, 'utf8');
  try {
    module.exports = JSON.parse(internalModule.stripBOM(content));
  } catch (err) {
    err.message = filename + ': ' + err.message;
    throw err;
  }
}
*/

require.extensions['.node'].toString()

/*
function (module, filename) {
  return process.dlopen(module, path._makeLong(filename));
}
*/

How module is wrapped?

Every module is wrapped by a function. Since the module is wrapped by this function, arguments returns array of exports, require, module, __filename, and __dirname.

require('module').wrapper

// [ '(function (exports, require, module, __filename, __dirname) { ',
//  '\n});' ]

https://stackoverflow.com/questions/46346502/require-resolve-works-why-doesnt-module-parent-require-resolve

https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8


exports

exports refers an object and associated to module.exports.

exports.name = "Kei"
// { name: "Kei" }

exports = { age: 28 }
// {}

module.exports = { foo: "bar" }
// { foo: "bar" }

fs

A module fs is acronym for File System and handling I/O in node.js.

readFile
readFileSync
createReadStream
writeFile
writeFileSync
createWriteStream
stat
open

Buffer and encoding

Before diving into each methods, take a look buffer and encoding. Suppose we read this text file.

// test.txt

Hello, I am text
var fs = require("fs");

fs.readFile("./test.txt", function (err, data) {
    if (err) throw err;
    console.log(data);
});

If no encoding is specified, then the raw buffer is returned. When we add encoding option, it reads file as utf-8 encoded file.

fs.readFile("./test.txt", { encoding: 'utf-8' }, function (err, data) {
    if (err) throw err;
    console.log(data); 
});
// Hello

readFile

readFile reads a file asynchronously, so callback function will be called after the file is read and put on memory.

fs.readFile('./test.txt', function (err, data) {
  if (err) throw err;
  console.log(data);
});

readFileSync

readFileSync reads a file synchronously.

var file = fs.readFileSync('./test.txt');

writeFile

writeFile method writes data to a file asynchronously.

fs.writeFile('test.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

writeFileSync

write file synchronously.

fs.writeFileSync('test.txt', 'Hello Node.js');

createReadStream

createReadFile reads file in chunked.

var stream = fs.createReadStream("./test.txt", "utf-8");

stream.on("data", function(data) {
  console.log(data);
});

stream.on("end", function(data) {
  console.log("end!");
});

createWriteStream

A writable stream is an abstraction of something we can send data to. It can be a file or a TCP connection.

var stream = fs.createWriteStream('./targetFile.txt', 'utf-8');
stream.on("data", function() {
  console.log(data)
});

stream.on('drain', function() {
  console.log('drain!');
})

drain event will be emitted when all buffer is cleaned up. Let's see the detail on Stream section.

open

flags
r open a text file for reading
r+ open a text file for reading and writing
rs Open for reading in synchronous mode
w Open for writing. If the file does not exist, it is created. If the file already exists, it is truncated.
w+ Open for reading and writing. If the file does not exist, it is created. If the file already exists, it is truncated.
wx Similar to the w flag, but the file is opened in exclusive mode. Exclusive mode ensures that the files are newly created.
a Open for appending. If the file does not exist, it is created.
a+ Open for reading and appending. If the file does not exist, it is created.

http://www.informit.com/articles/article.aspx?p=2266929&seqNum=3

results matching ""

    No results matching ""