Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect the entry file in Node.js?

Tags:

node.js

How can I detect the entry file in Node.js?

For example, if I launch my application by typing node file1.js, how can I tell that file1.js was the entry point?

like image 531
Chris Avatar asked Jul 26 '15 23:07

Chris


People also ask

How do I find the path of a file in node?

To check the path in asynchronous mode in the fs module we can use fs. stat() method. The fs. stat() method takes two parameters, first parameter is the path and the second is the callback function with two parameters, one is for error in case error occurred and the second parameter is the data retrieved by calling fs.

How do I check NodeJS files?

How to check JavaScript syntax from the command line. Node. js' --check option is available when running a JavaScript file. The command line flag turns the Node.

How do I read a file path in NodeJS?

var fs = require('fs'), path = require('path'), filePath = path. join(__dirname, 'start. html'); fs. readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (!

Which method is used to get file information in NodeJS?

fstat() functions. To get information about a file, we can use the fs. Stats object, which is returned by the fs. stat() , fs.


1 Answers

You can also use require.main.

Accessing the main module When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing

require.main === module

For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').

Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.

hot sauce

like image 156
Dan Avatar answered Nov 14 '22 21:11

Dan