

NODEJS REQUIRE CODE
I want to make sure my code is consistent/correct so which one do I use and why? Yes, if nodejs thinks you are using a CJS module. Using const fs = require('fs') works just fine You can also modify the package.json file that controls your particular script (by adding "type": "module" and force your file to an ESM module if you want (which allows you to use. If nodejs thinks you have a CJS file, you cannot use import (that is only for ESM modules). In nodejs, you have to tell nodejs in some way whether your top level module is CJS or ESM. Synta圎rror: Cannot use import statement outside a module When you see this image in the documentation, that lets you toggle the sample code in the doc from CJS to ESM or back.

You were apparently looking at the doc when it was showing ESM syntax. The current version of the fs documentation lets you pick whether you want the code examples to show CJS or ESM module syntax. When I look at the documentation for Node.JS for the file system "fs" module it doesn't make any mention of doing the const fs = require('fs) instead it talks about using the import method import from 'fs' If I was writing modules I wanted to share between nodejs and browsers, I'd pick ESM because it is supported in both.

If I was writing a quick "get it done" kind of script that relied on a bunch of scripts that are only available in CommonJS, I would probably use CommonJS require(). If I was starting a new project that I expected to last awhile and be working on it for years, I would pick ESM modules with import as that is the present/future architecture for modules in Javascript.
NODEJS REQUIRE HOW TO
Either way, you will probably run into some modules that are not of the type you chose for your project and will have to learn how to deal with that. import had some growing pains for awhile in nodejs, but the implementation is fairly complete now. You will generally want to pick one mechanism and use it for your whole project as it complicates things to mix/match. require() is natively supported in nodejs, but not in browsers (though there are some 3rd party libraries that have require-like module loaders for the browser). Require() is the original way that nodejs loaded modules and is used in CommonJS modules. Import is the future of the Javascript language in both nodejs and the browser and is used in ECMAScript modules (ESM modules) for loading other modules, either statically or dynamically.
