Hey there, amazing devs! π Today, weβre diving into two super useful features in Node.js: Importing JSON and Watch Mode. These features make development easier and more efficient, so letβs break them down in a fun and simple way! π
π₯ Importing JSON in Node.js
In many projects, we need to work with JSON data, like configuration files or API responses. Node.js makes it super easy to import JSON files directly! π
πΉ Traditional Way (Using require
)
Before ES Modules, the most common way to import JSON was using require
:
const config = require('./config.json');
console.log(config);
β
This works only in CommonJS (require
is not available in ES Modules).
πΉ Modern Way (Using import
)
If you're using ES Modules, you need to explicitly enable JSON imports by adding the assert
option:
import config from "./config.json" assert { type: "json" };
console.log(config);
β
This method works only in ES Modules (type: "module"
in package.json
).
πΉ Alternative: fs.readFileSync()
If you need to load JSON dynamically, use the File System (fs
) module:
import { readFileSync } from 'fs';
const data = JSON.parse(readFileSync('./config.json', 'utf8'));
console.log(data);
β Works in both CommonJS and ES Modules!
π Watch Mode (--watch
)
Tired of restarting your Node.js app manually after every change? Watch Mode is here to save the day! π
πΉ What is Watch Mode?
Watch Mode automatically restarts your Node.js application whenever you make changes to the source code. No more stopping and restarting manually! π
πΉ How to Use Watch Mode?
Simply add the --watch
flag when running your Node.js file:
node --watch app.js
Boom! Now, any time you edit and save app.js
, Node.js will restart automatically. π
πΉ Watch Mode with ES Modules
If you're using ES Modules, donβt forget to enable the type: "module"
setting in package.json
:
{
"type": "module"
}
Then run your script with:
node --watch app.js
β Works perfectly with ES Modules!
πΉ Watch Mode with CommonJS
For CommonJS, just run:
node --watch server.js
No extra setup needed!
π Final Thoughts
Both Importing JSON and Watch Mode make Node.js development smoother and faster. JSON imports keep your data handling clean, while Watch Mode saves you time by automatically restarting your app.
This is just the beginning! In the next article, weβll explore more Path Moduleβstay tuned! π―
If you found this blog helpful, make sure to follow me on GitHub π github.com/sovannaro and drop a β. Your support keeps me motivated to create more awesome content! π
Happy coding! π»π₯
Top comments (0)