Search This Blog

2024/03/19

Node.js :SyntaxError(Cannot use import statement outside a module)

Suppose you have a normal node.js file index.js as follows

index.js
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)

Explanation:
Here we are using import not commonly used in old style coding with common.js.
when you run the file as node index.js most probabally yoy will get error as
follows:

SyntaxError: Cannot use import statement outside a module

Solution:
You can resolve it by adding type as module in packgage.json as follows:
{
"name": "phenix",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"type": "module",
"license": "ISC",
"dependencies": {
"core-js": "^3.36.1"
}
}

2023/12/06

Javascript Interview Question:Matching Parenthesis


Problem Statement:

Given a string s containing just the characters '(', ')', '{', '}', '['
and ']',determine if the input string is valid.

An input string is valid if:

1) Open brackets must be closed by the same type of brackets.
2) Open brackets must be closed in the correct order.
3) Every close bracket has a corresponding open bracket of the same type.

Example 1:
Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false

Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.


Solution:
var str = "([{{([{([])}])}}]) [({})]";

function wellFormedBrackets(str) {
var circular = 0;
var rectangular = 0;
var curly = 0;

var brackets = {
"[": "]",
"(": ")",
"{": "}",
};

var lastOpening = [];
var lastOpeningChar = "";

for (var char of str) {
if (char == "[" || char == "(" || char == "{") {
lastOpening.push(char);

if (char == "[") {
rectangular++;
}
if (char == "{") {
curly++;
}
if (char == "(") {
circular++;
}
}

if (char == "]" || char == ")" || char == "}") {
lastOpeningChar = lastOpening.pop();
console.log("one:", lastOpeningChar);
console.log("two", char);

if (lastOpeningChar == undefined) {
console.log("No Opening brace");
return false;
} else {
if (brackets[lastOpeningChar] == char) {
if (char == "]") {
rectangular--;
}
if (char == "}") {
curly--;
}
if (char == ")") {
circular--;
}
} else {
console.log("Bracket are not properly nexted");
return false;
}
}
}
}

if (circular + rectangular + curly == 0) {
return true;
} else {
return false;
}
}

var result = wellFormedBrackets(str);
console.log("Result is", result);