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?
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 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.
var fs = require('fs'), path = require('path'), filePath = path. join(__dirname, 'start. html'); fs. readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (!
fstat() functions. To get information about a file, we can use the fs. Stats object, which is returned by the fs. stat() , fs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With