Search This Blog

2024/03/19

Node.js:Difference between *.mjs, *.cjs, and *.js files



 Most of the time javascript files in node.js project have .js extension.

In Node.js, a file is treated as a "module". JavaScript code in one module
(file) can't be seen from another module (file), unless one module explicitly
exports functionality and the other module explicitly imports that functionality.

There are two common systems for imports and exports in Node: Common.js Modules
and ES Modules.

By default, Node.js will expect Common.js-style modules for files that have a .js or .cjs extension.
To use ES modules .mjs file extension required.

If you want to use file with .js extension in ES module then
set "type" to "module" in the package.json.


Here is index.mjs but "type" is absent in package.json

import "core-js";


const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];

const result = inventory.group(item=>{
return item.type
})
console.log(result)


const result2 = inventory.groupByToMap(item=>{
return item.type == "meat"?"Non-Veg":"Veg"
})
console.log(result2)


when we ran it as

node index.mjs

we get following output

[Object: null prototype] {
vegetables: [ { name: 'asparagus', type: 'vegetables', quantity: 5 } ],
fruit: [
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
],
meat: [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 }
]
}
Map(2) {
'Veg' => [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
],
'Non-Veg' => [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 }
]
}

Other way is rename index.mjs as index.js but set "type" as module in package.json

Now we can run it as

node index.js

output of this file will be same as previous one.

No comments:

Post a Comment