DotEnv comments are crashing - node.js

I'm using dotenv version 16.0.0 in my NodeJS project but the comment feature that was recently added causes a crash. Without the comments the .env file works perfectly, loading values from it.
The .env file content:
# Print out information during runtime, useful for debugging problems not caught.
(true/false)
VERBOSE=false
# Database settings, update for actual deployment environment
DB_USERNAME=postgres
DB_PASSWORD=TINY_DUCK
DB_NAME=user_database
DB_HOST=localhost
DB_PORT=5432
The command to run the NodeJS project is:
mocha -r .env ./tests/testManager.js --exit
And the error message I get when running the NodeJS project:
× ERROR: C:\Users\thega\Source\Repos\network\.env:1
# Print out information during runtime, useful for debugging problems not caught. (true/false)
^
SyntaxError: Invalid or unexpected token
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at exports.requireOrImport (C:\Users\thega\source\repos\network\node_modules\mocha\lib\nodejs\esm-utils.js:60:20)
at async exports.handleRequires (C:\Users\thega\source\repos\network\node_modules\mocha\lib\cli\run-helpers.js:94:28)
at async C:\Users\thega\source\repos\network\node_modules\mocha\lib\cli\run.js:353:25

It looks to me as if you are trying to import the .env file as JS module instead of loading it with the dotenv package.
The -r flag to mocha means "require":
This will require a module before loading the user interface or test files.
It is useful for:
Test harnesses
Assertion libraries that has augment built-ins or global scope (such as should.js)
Instant ECMAScript modules using esm
Compilers like Babel via #babel/register or TypeScript using ts-node (using --require ts-node/register).
So it will try to load the file as JavaScript and of course that can't work.
Instead, you can require dotenv/config so it will parse the file for you and update process.env accordingly:
mocha -r dotenv/config ./tests/testManager.js --exit
Or, if you already do require('dotenv').config() in your code, you don't need any -r switch here at all.

Related

Deployement Nuxt.js ssr on passenger : SyntaxError: Cannot use import statement outside a module

I'm deploying my nuxt app on planethoster who use Passenger to run Node.js Application. I build the app by using ">npm run build" and deployed the content off .nuxt folder on the server, with "server.js" as entrypoint. but I ran on the following error:
/home/scalcmjx/test.scalomhouseplans.com/server.js:1
import Vue from 'vue'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at Module.require (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:80:25)
at require (internal/modules/cjs/helpers.js:74:18)
at loadApplication (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:243:2)
at setupEnvironment (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:214:2)
Please Someone know how to manage it?
What is your node.js version? Try using the current LTS: 14.17.0
If I'm not mistaken, the import syntax is officially supported since v14, so this should maybe fix one issue.
Also, you need to deploy dist and not .nuxt, the latter is used for caching purposes.
I'm not sure of what is the process for this specific host, but you should probably get some decent ideas from the deployment section of the official documentation: https://nuxtjs.org/docs/2.x/deployment/deploying-to-21yunbox
There are a lot of hosting solutions there, one is probably looking like Planethoster.

ECMAScript Modules On Node.js v11.9.0

I'm trying to use exports and import on Node.js application, So I used the Node.js documentation ECMAScript Modules. But I am getting error
I am using,
v11.9.0
Run command node --experimental-modules app.js
How can I use ES6 export and import in Node.JS ? Preferred me the way that not using any additional package !
Code :
// test.js
module.exports = { one: 1 };
// app.js
import foo from './test.js';
console.log(foo);
Error :
(node:9352) ExperimentalWarning: The ESM module loader is experimental.
/home/Workspace/test/app.js:1
(function (exports, require, module, __filename, __dirname) { import foo from './test.js';
^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:84:7)
at createScript (vm.js:264:10)
at Proxy.runInThisContext (vm.js:312:10)
at Module._compile (internal/modules/cjs/loader.js:694:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
at Module.load (internal/modules/cjs/loader.js:626:32)
at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
at Function.Module._load (internal/modules/cjs/loader.js:558:3)
at createDynamicModule (internal/modules/esm/translators.js:73:15)
at Object.meta.done (internal/modules/esm/create_dynamic_module.js:40:9)
As the doc says your files need a .mjs extension:
The --experimental-modules flag can be used to enable features for
loading ESM modules.
Once this has been set, files ending with .mjs will be able to be
loaded as ES Modules.
You have to currently use the flag and there is no "seamless" way to use them at the moment other than using a transpiler like babel.
As Quentin says CommonJS files can still use .js extension (you can mix and match).

Version compatibility issue Azure functions' Node and DirectlineJS es6 exports

End Goal:
To create Azure Function running Botframework-DirectlineJS with binding to Bot (Framework) using DirectLine secret.
Issue:
The above mentioned Botframework-DirectlineJS uses ES6 export and Azure Functions support Node 6.5.0 max doc. Hence the question how to import successfully the DirectlineJS in the index.js file of Azure function?
Error
```
2017-05-23T07:17:45.939 Exception while executing function: Functions.adapter. mscorlib: D:\home\site\wwwroot\adapter\importexportwrapper.js:1
(function (exports, require, module, __filename, __dirname) { import { DirectLine } from 'botframework-directlinejs';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:528:28)
at Object.Module._extensions.(anonymous function) [as .js] (D:\home\site\wwwroot\node_modules\node-hook\index.js:73:14)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.require (module.js:483:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\home\site\wwwroot\adapter\index.js:4:2)
at Module._compile (module.js:556:32).
```
Currently the error was while trying to use npm import-export
Files
index.js
require('import-export');
require ('./importexportwrapper');
let directLine = new DirectLine({
secret: 'DirectlineSecretValue-here'
}
);```
importexportwrapper.js
import { DirectLine } from 'botframework-directlinejs';
Unfortunately it seems like import-export or node-hook doesn't play well with functions / edgejs (the environment we use to run node).
A couple options to try:
use babel to transpile es6 to es5 as a part of your deployment process.
write your function in typescript (index.ts) which will do import transpilation automatically - though this may fail for module dependencies, I haven't tried it out
You have three options: 1) Write your code using ES5, 2) setup a task runner (gulp/grunt/npm scripts) to convert your ES6+ code to ES5 using Babel, or 3) write your code in Typescript and compile it to ES5 via task runner/npm scripts.
The most straight-forward method would be: in your file importexportwrapper.js use require instead of import.
Example:
var directline = require('botframework-directlinejs');
Babel + Gulp Option
Install: npm install --save-dev gulp gulp-babel
Run:
var gulp = require("gulp");
var babel = require("gulp-babel");
gulp.task("default", function () {
return gulp.src("src/app.js") // your source files
.pipe(babel())
.pipe(gulp.dest("dist")); // your compiled output directory
});
Read more about Azure Functions Node.js versions here.

TypeScript external node modules sometimes transpile to module.exports and exports

I'm in the process of converting my node app to use TypeScript external modules. Everything works fine when running the app but when converting some of my .ts files, the mocha tests "explode" due to SyntaxError: Unexpected reserved word.
After much debugging, I've found the following reproducible failure case. I have a simple autoRoles.ts file that defines the available user roles. Prior to using external modules, it looked like:
/// <reference path="../../typings/backend_typings.d.ts" />
module.exports.roles = {
// role definitions
}
Now after the conversion:
/// <reference path="../../typings/backend_typings.d.ts" />
export let roles = {
// role definitions
}
When running the mocha tests, it generates the following error:
>> Mocha exploded!
>> SyntaxError: Unexpected reserved word
>> at exports.runInThisContext (vm.js:53:16)
>> at Module._compile (module.js:413:25)
>> at Object.Module._extensions..js (module.js:452:10)
>> at Module.load (module.js:355:32)
>> at Function.Module._load (module.js:310:12)
>> at Module.require (module.js:365:17)
>> at require (module.js:384:17)
>> at Object.<anonymous> (/Users/abc/esupport/code/asp_v4/lib/models/userRole.ts:77:17)
>> at Module._compile (module.js:434:26)
>> at Object.Module._extensions..js (module.js:452:10)
>> at Module.load (module.js:355:32)
>> at Function.Module._load (module.js:310:12)
>> at Module.require (module.js:365:17)
>> at require (module.js:384:17)
>> at Object.<anonymous> (/Users/abc/esupport/code/asp_v4/lib/users/lib/ssoAuth.ts:7:17)
>> at Module._compile (module.js:434:26)
>> at Object.Module._extensions..js (module.js:452:10)
>> at Module.load (module.js:355:32)
>> at Function.Module._load (module.js:310:12)
>> at Module.require (module.js:365:17)
>> at require (module.js:384:17)
>> at Object.<anonymous> (/Users/abc/esupport/code/asp_v4/lib/users/index.ts:5:31)
I can flip between the old implementation and the new implementation for the autoRoles.ts file and get mocha to pass and fall, respectively. Note, there is a require('<path>/autoRoles') on line 77 of userRoles.ts.
When comparing between the transpiled versions, the only difference is that the old version uses 'module.exports' and the new one just has 'exports'.
Old:
/// <reference path="../../typings/backend_typings.d.ts" />
exports.roles = {
// role definitions
}
New:
/// <reference path="../../typings/backend_typings.d.ts" />
module.exports.roles = {
// role definitions
}
So I'm aware that "exports" is just a shortcut to "module.exports" so I can't explain why this is causing mocha to fail but I do know that if I switch between the two and change nothing else, mocha "explodes". I've also noticed that for other transpiled modules, tsc sometimes uses "module.exports" and sometimes uses "exports". Why the difference and more importantly, why is mocha exploding?
Unexpected reserved word
Have "use strict"; at the top of your file. You probably have a variable that is a reserved keyword. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Paving_the_way_for_future_ECMAScript_versions . TypeScript will warn on such variable names if you have that header in the file.
module.exports.roles = { is not the source of your error.
I've also noticed that for other transpiled modules, tsc sometimes uses "module.exports" and sometimes uses "exports".
Its similar to the nodejs convention. Basically saving characters (bytes) the runtime needs to parse.
export let foo = 123;
Will give you
exports.foo = 123;
(because exports == module.export therefore exports.foo == module.export.foo ... as you already know). However in :
let foo = 123;
export = foo;
It does
var foo = 123;
module.exports = foo;
Because if you reassign exports i.e. exports = foo then module.export !== exports. So you can use exports for extension .... but not assignment.
After more debugging, I found that mocha wasn't using the generated .js source code files that tsc transpiled. I'm not sure exactly how but it was trying to execute the "export var roles" located in the .ts file and "export" is a reserved word.
I came across this post, which indicated to me that mocha is trying to do it's own transpiling. That guy suggested to use "typescript-require" but that package looks like in the middle of being deprecated in favor of "ts-node". So I changed my grunt-ts config to look like:
mochaTest: {
test: {
options: {
reporter: 'spec',
require: [
'ts-node/register'
]
},
src: ['lib/test/**/*.spec.js']
}
},
This works but I'd be more than happy to have someone shed some light on what mocha was doing. Also, why was mocha successfully transpiling / not detecting "reserved word" in other .ts files that used export?
Edit 10/30/2015:
So I found out why mocha was trying to execute my .ts files. I was stupidly importing some of them as require('/path/file.ts') where I should have left the '.ts' extension off. I no longer need 'ts-node' in my mocha runner. This also explains why mocha was only erroring on some of my .ts files.

NODE_PATH is being ignored or not working

I'm trying to run my node app on a new server and am having some issues with the NODE_PATH environment variable. The app works fine on my local machine (OSX Lion) but not on the server (Redhat linux). When starting my app with node app.js from within my project directory /development/nodeproject, I get the following error :
Error: Cannot find module 'mod/core/models/Category'
at Function._resolveFilename (module.js:334:11)
at Function._load (module.js:279:25)
at Module.require (module.js:357:17)
at require (module.js:368:17)
at /development/nodeproject/app.js:57:5
at Object.<anonymous> (/development/nodeproject/app.js:258:1)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
mod/core/models/Category is the first require() in my app.js and looks like this: var Category = require('mod/core/models/Category'). So apparently node is not looking for modules in my project directory.
I'm not sure why though, because I made the following changes (that are working just fine on my local machine).
added export NODE_PATH=/development/nodeproject to my ~/.bash_profile
ran source ~/.bash_profile
if I run env I see NODE_PATH=/development/nodeproject listed there
in my app.js if I console log process.env.NODE_PATH I get /development/framework (should this output an array instead of a string?)
Other information that might be relevant:
I'm on node v0.6.7
I'm doing all of this as root (sudo su -)
At this point I'm not sure what else I can do. Any help would be greatly appreciated.
NODE_PATH used for modules, not for solutions files.
Try
module.paths.push("/development/nodeproject", "one/more/path");
before any require() call. And you really should use a relative require like require('./mod/core/models/Category') for files in your nodeproject directory
The functionality you are looking for was removed. Use the node_modules directory or a relative require like require('./mod/core/models/Category').
This answer has more info: NODE_PATH error with node.js while attempting to setup jsctags for vim

Resources