how can i get list of all files in a current directory with node.js and esm syntax?
- User
how can i get list of all files in a current directory with node.js and esm syntax?
- Assistant
To list all files in a current directory using Node.js with ECMAScript Modules (ESM) syntax, you'll first need to ensure that your project supports ESM. You can do this by either naming your file with a
.mjsextension or by setting"type": "module"in yourpackage.jsonfile.Here, I'll guide you through creating a simple script that lists all the files in the current directory using ESM syntax:
-
Set Up Your Project: Make sure your Node.js environment supports ESM.
-
Create a
package.json(if it doesn't already exist) usingnpm init -y. -
Add
"type": "module"to yourpackage.json:{ "name": "your-project-name", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
-
-
Create Your Script:
Create a file named
listFiles.mjs(orlistFiles.jsif you've set"type": "module"in yourpackage.json). -
Write the Script to List Files:
You will utilize the
fsmodule withpromisesAPI to read the contents of the directory. Here’s how you can do it:// Import the fs/promises module import { readdir } from 'fs/promises'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; // Get the directory name from the module URL (since __dirname is not available in ES modules) const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); async function listFiles() { try { // Read the contents of the directory const files = await readdir(__dirname); console.log("Files in the current directory:", files); } catch (err) { console.error('Error reading directory:', err); } } listFiles();- This script uses the
readdirfunction from thefs/promisesAPI to asynchronously list all files and directories in the current directory. import.meta.urlgives you the URL of the current module which is used to derive__dirnamesince it’s not available directly in ES Modules.
- This script uses the
-
Run Your Script:
Run your script using Node.js by executing:
node listFiles.mjsor
node listFiles.jsif you used the
.jsextension with the"type": "module"in yourpackage.json.
This script will output all the files and directories in the folder where the script resides. Adjust the path in
readdir()if you need to list files from a different directory. -