简体   繁体   中英

How are absolute or relative file paths of the custom modules resolved in node.js?

require doesn't seem to take any path other than './parser1' . I have placed both the js files in Desktop. I ran node my_parser.js , it always threw me an error saying "Cannot find module" for relative path require('parser1') or absolute path require('Desktop/parser1').

Why does it resolve the file path only with require('./parser1' ? What is the configurations behind it?

Please find the code below:

 // Require my new parser.js file.
var Parser = require('./parser1');

var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('Desktop/example_log.txt', function (err, logData) {

// If an error occurred, throwing it will
  // display the exception and end our app.
  if (err) throw err;

// logData is a Buffer, convert to string.
  var text = logData.toString();

  // Create an instance of the Parser object.
  var parser = new Parser();

  console.log(parser.parse(text));
});

parser1:

// Parser constructor.
var Parser = function() {

};

// Parses the specified text.
Parser.prototype.parse = function(text) {

var results = {};

// Break up the file into lines.
  var lines = text.split('\n');

lines.forEach(function(line) {
    var parts = line.split(' ');
    var letter = parts[1];
    var count = parseInt(parts[2]);

if(!results[letter]) {
      results[letter] = 0;
    }

results[letter] += parseInt(count);
  });

return results;
};

// Export the Parser constructor from this module.
module.exports = Parser;

require(..) can be used with one of two path types:

  • path relative to current fle
  • name of installed package

Relative path:

Relative path begins with a dot + slash ( './' ) and then you put actual relative position of required file: ./path/to/your/module

Installed package name

If, on the other hand you choose to use require directly with package name, eq. require('express') , node looks for a specific folder that keeps installed modules: node_modules . Once it finds matching one, it is imported. If none of the packages match, node tries to find another node_modules folder one level above in your OS file system. If it fails to find anything, it raises the error you've got.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM