Have problem using export function in node js [duplicate] - node.js

This question already has answers here:
Node.js - SyntaxError: Unexpected token import
(16 answers)
Closed 1 year ago.
The code for pug.compiler.js is:
/**
* Pug Utilities
*/
const {compileFile} =require('pug');
/**
*
* #param {String} relativeTemplatePath Pug template name
* #param {Object} [data] Object
* #returns {String} HTML
*/
export function compile(relativeTemplatePath, data){
let absoluteTemplatePath = process.cwd() + '/src/views/' + relativeTemplatePath + '.pug';
let compiledTemplate = compileFile(absoluteTemplatePath)(data);
return compiledTemplate;
};
The error is :
export function compile(relativeTemplatePath, data){
^^^^^^
SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:984:16)
at Module._compile (internal/modules/cjs/loader.js:1032:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (D:\ProgramData\projects\nodejs\whatsapp\test\app.js:11:22)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
So I have a problem understanding how do I use this export function. I think it should work right?

The problem is NodeJS considers module by default as CommonJS Modules.
So instead of export you should use module.exports, or if you're using NodeJS v13+ you can enable ES Modules by either:
Changing the extension of your file to mjs
Adding "type": "module" property to your package.json
Using module.exports should be like:
function compile(relativeTemplatePath, data){
let absoluteTemplatePath = process.cwd() + '/src/views/' + relativeTemplatePath + '.pug';
let compiledTemplate = compileFile(absoluteTemplatePath)(data);
return compiledTemplate;
};
module.exports = {compile};

Related

Firebase Schedule Functions giving error when deploy

I was referring Firebase documentation for cloud function to schedule a function. But It was giving following error when try to deploy.
Error: Error occurred while parsing your function triggers.
token-refresh/functions/index.js:5
export scheduledFunction = functions.pubsub.schedule('5 23 * * *').onRun((context) => {
^^^^^^
SyntaxError: Unexpected token export
at Module._compile (internal/modules/cjs/loader.js:743:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
at Module.load (internal/modules/cjs/loader.js:666:32)
at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
at Function.Module._load (internal/modules/cjs/loader.js:598:3)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:15:15
at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:53:3)
at Module._compile (internal/modules/cjs/loader.js:799:30)
I just tried to deploy exact function that is in documentation, but it is giving error.
My Code I tried to deploy,
const functions = require('firebase-functions');
export scheduledFunction = functions.pubsub.schedule('5 23 * * *').onRun((context) => {
console.log('This will be run at 23.05 UTC');
});
My versions:
Firebase/ firebase-tools: 7.0.0
node: 11.11.0
npm: 6.7.0
Documentation
https://firebase.google.com/docs/functions/schedule-functions
The following should work:
const functions = require('firebase-functions');
exports.scheduledFunction = functions.pubsub.schedule('5 23 * * *').onRun((context) => {
console.log('This will be run at 23.05 UTC');
});
See https://firebase.google.com/docs/functions/get-started and https://cloud.google.com/functions/docs/writing/

Error while importing one file into another in Node.JS

I am using import while importing some functions from my practice.js file into different.js file.
practice.js file:-
function sum(x,y){
return x+y;
}
const pi = 3.14;
module.exports = {
sum : sum,
pi:pi
};
different.js file:-
import {sum,pi} from "./practice.js";
console.log("2 pie: "+sum(pi,pi));
Now when I am using require, the output is proper and no error is given.
When I am using import, there is this following error:-
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:749:23)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:816:10)
at Module.load (internal/modules/cjs/loader.js:672:32)
at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
at Function.Module._load (internal/modules/cjs/loader.js:604:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:868:12)
at internal/main/run_main_module.js:21:11
I have asked my colleagues and they told me that this is about ES6 and Babel is not configured in your system.
But I am not sure how to proceed with this. Can anybody please help me how to do it?
Rename your main file (different.js) to different.mjs.
Rename your practice.js file to practice.mjs and make it look like this:
function sum(x, y) {
return x + y;
}
const pi = 3.14;
export {sum, pi};
Then run node --experimental-modules different.mjs to run Node with it's experimental module loader.
You can read more here

Alexa Lambda Function "Unable to import module 'index'" when using new required function

I'm building an Alexa skill (deploying via CLI), and all has been going well up until needing to make a few Http calls.
I decided to use first axios, then require in order to do so.
When I installed axios using npm, all seemed well. Adding just the "const axios= require('axios');" line caused my lambda function to start complaining about "Unable to import module 'index'" in the Cloudwatch logs, however, and specifically calling out the line in index.js where I make that require statement.
Removed axios, tried require...same deal.
Any thoughts?
Not actually using the packages yet even, it complains on the require line if I uncomment it.
/* eslint-disable func-names */
/* eslint-disable no-console */
/* eslint-disable no-restricted-syntax */
const error_handler = require('./error_handler');
const globals = require('./globals');
const helper_functions = require('./helper_functions');
const intents_aquarium = require('./intents_aquarium');
const intents_built_in = require('./intents_built_in');
const intents_conversion = require('./intents_conversion');
const intents_helper = require('./intents_helper');
const intents_tank = require('./intents_tank');
const intents_unhandled = require('./intents_unhandled');
const skillBuilder = globals.Alexa.SkillBuilders.standard();
//const request = require('request');
exports.handler = skillBuilder
.addRequestHandlers(
intents_built_in.launchRequest,
intents_built_in.exitHandler,
intents_built_in.sessionEndedRequest,
intents_built_in.helpIntent,
intents_built_in.yesIntent,
intents_built_in.noIntent,
intents_aquarium.aquariumCreateIntentHandler,
intents_aquarium.aquariumCreateSimpleImperial,
intents_conversion.aquariumVolumeIntentGallonsToLitres,
intents_conversion.aquariumVolumeIntentLitresToGallons,
intents_helper.thankYou,
intents_tank.tankObservation,
intents_built_in.fallbackHandler,
intents_unhandled.unhandledIntent,
)
.addErrorHandlers(error_handler.errorHandler)
.withTableName('Tank-Mate')
.withAutoCreateTable(true)
.lambda();
Error looks like this:
Unable to import module 'index': Error
at Function.Module._resolveFilename (module.js:547:15)
at Function.Module._load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/var/task/index.js:16:17)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
...which to me looks like it's complaining about the index.js require line.

How do you import a function with parameters using ECMAScrip6?

I am setting up a brand new project in Express using Babel and ESLint, and am trying to setup dynamic routes. The only issue is that I cannot figure out how to call the loader for the routes. This is my current code regarding the loader.
routes/index.js
import fs from 'fs';
/**
* Register Default Routes
* #param {Object} app express.Application
*/
export default function(app) {
fs.readdirSync(__dirname).forEach((fileName) => {
if (fileName == __filename.slice(__dirname.length + 1)) return;
let fileNameStripped = fileName.substring(0, fileName.lastIndexOf('.'));
require('./' + fileNameStripped)(app); // does not work
});
}
index.js
import express from 'express';
import routes from './routes/index.js';
const app = express();
app.use(express.static('public'));
routes(app); // works now
...
Babel Error
TypeError: require(...) is not a function
at /app/build/routes/index.js:1:314
at Array.forEach (<anonymous>)
at exports.default (/app/build/routes/index.js:1:195)
at Object.<anonymous> (/app/build/index.js:1:393)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Function.Module.runMain (module.js:690:10)
The issue appears to be related to https://github.com/babel/babel/issues/2683
Since nested route files are supposed to be ES modules with default exports, require('./' + fileNameStripped) is module object and not a function. It should be:
require('./' + fileNameStripped).default(app);
Depending on Babel configuration (dynamic-import-node plugin is required), require() can be replaced with dynamic import() but it's less desirable here, because dynamic import is not synchronous and can cause race conditions.

Unexpected token =

I'm unsure as to what could cause this error in Node.js, as I've never seen it before and cannot find another issue online.
Message:
Unexpected token =
Stack:
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (/Projects/api/test/integration/models/article.js:3:15)
The file that is causing the error has the following contents:
'use strict';
var Article = require('../../../models/article')
Why in the world would = cause an error?
Edit 1 - adding the article.js that is being required:
'use strict';
class ArticleModel {
constructor(options = {}) {
this.options = options
}
}
module.exports = ArticleModel
node.js 5.0 does not support all ES6 features yet. In particular, it does not yet support default parameters.
So this line:
constructor(options = {}) {
is what is causing the error with the = assignment.
See this table for which features are supported in node.js 5.0.
You can replace the default parameter assignment with the old fashioned method:
constructor(options) {
this.options = options || {};
}
I think, your current Node.js distribution doesn't support default parameter values.
You should remove it:
constructor(options) {
this.options = options || {};
}
Or, try to play with --harmony runtime flag.
According to this link --harmony can not to help, this feature doesn't implemented in node5.0 at all.
I am using Node v5.7.0 and can enable default parameters using this option:
--harmony-default-parameters
The error is on the 3rd line of article.js.

Resources