Why readings from .env file are wrong? - node.js

I've a problem. I'm new to nodejs so probably it's really easy to fix it. In the main directory, I've a .env file. In the main.js file I've:
const express = require('express');
const app = express();
const http = require('http')
const {Pool, Client} = require('pg');
require("dotenv").config();
console.log(process.env.USER);
So, I simply want to print the USER variabile that is located into my .env file. Here is my .env file:
USER=postgres
HOST=localhost
DATABASE=postgres
PASSWORD=mysecretpassword
PORT=5432
Anyway, when I write console.log(process.env.USER);, the variable printed is not the USER variable (that is postgres), but my pc user account (that is John). How is that possible?

I don't have enough reputation to comment, but have you tried renaming your variables, adding a prefix like DB_, so the variables names become DB_USER, DB_HOST etc.?
Maybe this variable is already taken by the process. And I personally don't like to overwrite them.
You can check running node REPL in your terminal, then typing process.env.
These are the Node environment variables that are already taken on my PC (running on Windows):
{
ALLUSERSPROFILE: 'C:\\ProgramData',
APPDATA: 'C:\\Users\\dizolan\\AppData\\Roaming',
ChocolateyInstall: 'C:\\ProgramData\\chocolatey',
CommonProgramFiles: 'C:\\Program Files\\Common Files',
'CommonProgramFiles(x86)': 'C:\\Program Files (x86)\\Common Files',
CommonProgramW6432: 'C:\\Program Files\\Common Files',
COMPUTERNAME: '...',
ComSpec: 'C:\\Windows\\system32\\cmd.exe',
DriverData: 'C:\\Windows\\System32\\Drivers\\DriverData',
FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
FPS_BROWSER_USER_PROFILE_STRING: 'Default',
GOPATH: '...',
HOMEDRIVE: 'C:',
HOMEPATH: '...',
LOCALAPPDATA: '...',
LOGONSERVER: '...',
NUMBER_OF_PROCESSORS: '8',
OneDrive: '...',
OS: 'Windows_NT',
Path: '...',
PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW',
POWERSHELL_DISTRIBUTION_CHANNEL: 'MSI:Windows 10 Pro for Workstations',
PROCESSOR_ARCHITECTURE: 'AMD64',
PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 142 Stepping 12, GenuineIntel',
PROCESSOR_LEVEL: '6',
PROCESSOR_REVISION: '8e0c',
ProgramData: 'C:\\ProgramData',
ProgramFiles: 'C:\\Program Files',
'ProgramFiles(x86)': 'C:\\Program Files (x86)',
ProgramW6432: 'C:\\Program Files',
PSModulePath: 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules',
PUBLIC: 'C:\\Users\\Public',
SESSIONNAME: 'Console',
SystemDrive: 'C:',
SystemRoot: 'C:\\Windows',
TEMP: '...',
TMP: '...',
USERDNSDOMAIN: '...',
USERDOMAIN: '...',
USERDOMAIN_ROAMINGPROFILE: '...',
USERNAME: '...',
USERPROFILE: '...',
windir: 'C:\\Windows'
}

dotenv add override option at version 14.1.0 (2022-01-17) You can use override: true option to
Override any environment variables that have already been set on your machine with values from your .env file.
require('dotenv').config({ override: true, debug: true })
console.log(process.env.USER);
Output:
[dotenv][DEBUG] "USER" is already defined in `process.env` and WAS overwritten
postgres
USER is a system environment variable, see environ(7)
USER The name of the logged-in user (used by some BSD-derived
programs). Set at login time, see section NOTES below.

Related

"Cannot use import statement outside a module" in typeorm migration when run nestjs app

I have created the nestjs app. In the root app folder I have these subfolders:
dist
migration
src
test
The migration folder contains typeorm migrations.
When run application with npm run start:dev I have this error:
import {MigrationInterface, QueryRunner} from "typeorm";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Function.PlatformTools.load (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\platform\PlatformTools.js:114:28)
at C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:69
at Array.map (<anonymous>)
at Object.importClassesFromDirectories (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:10)
I understand the error message and I know how to fix it when it relates to application's code.
However, my problem is that this error come from typeorm migration file: [app-root-folder]\migration\1587067680466-Init.ts which shouldn't be used when application runs.
Why nestjs uses migration files. How can I ignore migration folder when running nestjs app?
to solve it just put the following code on your "scripts" at package.json:
"typeorm": "ts-node-dev ./node_modules/typeorm/cli.js",
After that you'll be able to run your typeorm migration:run :)
I found the solution:
This happends to me because I was using Nest and when you run the command nest start, under the hood, Nest executes node and tsc and node commands and because of that you need your files to be in JavaScript format. So, as the migrations are generated in Typescript... the statement import gives the error because is only for TypeScript.
The only thing i did to solve it is this:
migrations: ["dist/migrations/*.js"],
This is telling TypeOrm that search for the migration in the dist directory where all the JavaScript code was compiled previously.
Of course in my tsconfig.json file the output dir is pointing to dist.
"outDir": "./dist",
I had the same issue. I did the following as a workaround:
Set your ormconfig.json to look for migrations files with only js suffix:
"migrations": ["migrations/*.js"],
Install typescript globally: npm install -g typescript
After generating your migration, transpile typescript files to javascript files with typescript command:
tsc migrations/migration-file.ts
Run your migration: npm run typeorm migration:run
You can now run your application: npm run start:dev
I know this question is old, but I just came across it because I had the same problem. I was able to solve it by adding "migration/**/*.ts" to the "exclude" array in the /tsconfig.build.json file like so:
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts", "migration/**/*.ts"]
}
The same issue here, and in my case the root cause was a wrong migrations path in the connection configuration, like this;
const databaseConfig: ConnectionOptions = {
name: 'default',
type: 'postgres',
host: process.env.TYPEORM_HOST || '',
port: Number(process.env.TYPEORM_PORT),
username: process.env.TYPEORM_USERNAME || '',
password: process.env.TYPEORM_PASSWORD || '',
database: process.env.TYPEORM_DATABASE || '',
logging: false,
synchronize: false,
entities: [],
migrations: ['src/migrations/*.ts'],
};
Instead, I have changed it to
const migrationPaths: string[] = process.env.TYPEORM_USE_CLI === 'true' ? ['src/migrations/*{.ts,.js}'] : [];
const databaseConfig: ConnectionOptions = {
name: 'default',
type: 'postgres',
host: process.env.TYPEORM_HOST || '',
port: Number(process.env.TYPEORM_PORT),
username: process.env.TYPEORM_USERNAME || '',
password: process.env.TYPEORM_PASSWORD || '',
database: process.env.TYPEORM_DATABASE || '',
logging: false,
synchronize: false,
entities: [],
migrations: migrationPaths,
};
another test you can try to see if the problem is really with migration is to move the migration filter out of src.
For TypeORM v0.3.0 or higher, glob patterns in migrations are DEPRECATED. It is recommended to directly include the migration classes.
entities, migrations, subscribers options inside DataSourceOptions accepting string directories support is deprecated. You'll be only able to pass entity references in the future versions.
import { DataSource, DataSourceOptions } from 'typeorm';
import { CreateUser1669370712331 } from '../../migrations/1669370712331-CreateUser';
import { UserModify1669457039074 } from '../../migrations/1669457039074-UserModify';
import { User } from '../users/entities/user.entity';
export const config: DataSourceOptions = {
type: 'sqlite',
database: 'db/database.sqlite',
logging: true,
synchronize: false,
entities: [User],
migrations: [CreateUser1669370712331, UserModify1669457039074],
};

How to execute locally installed Node.js application by child_process.spawn()?

I want to execute the Electron application by child_process.spawn:
import ChildProcess, {ChildProcess as ChildProcess__type} from 'child_process';
const childProcess: ChildProcess__type = ChildProcess.spawn(
'electron',
['ProjectInitializer__ElectronMain.js'],
{ cwd: __dirname } // current project root
);
I got Error: spawn electron ENOENT error. Electron has been installed locally, AFAIK is the good practice. Also, electron ProjectInitializer__ElectronMain.js works, it to execute this console command from my project directory.
Following frequently up-voted ENOENT error debugging guidance, I got the cause: there is no directory among process.env.PATH, which includes electron.
I know about PATH variable not much, so I can not answer what must be in this variable and what is not. But what I want to ask is: how to execute locally installed (in node_modules) Node.js applications (like electron)?
By the way, execa which is known as improved child_process runs electron without errors (update: version 2.x.x already do not runs):
import executeExternalCommand, { ExecaReturnValue } from 'execa';
try {
await executeExternalCommand(
'electron',
['ProjectInitializer__ElectronMain.js'],
{ cwd: __dirname }
);
} catch (error) {
console.error(error);
}
Somehow, thanks to { cwd: __dirname }, the execa v 1.x.x knows, where should to find the electron. Unfortunately, execa has too small community and small documentations, so stopped to use it.
Additional information
How I run this Node.js script which has the spawn parameter
By command my-library init which I created.
In package.json:
"bin": {
"my-library": "bin/my-library"
}
In bin/my-library (no filename extension):
#!/usr/bin/env node
require('../CLI').interpretConsoleCommandAndExecute(process.argv);
In CLI.js I parse the console command, and if it is the my-library init, I'll try to execute
const childProcess: ChildProcess__type = ChildProcess.spawn(
'electron',
[ 'ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname }
);
console.log(process.env) output
Below output is for PhpStorm build-in console, however in other consoles, e. g. in cmder, output is different.
{ FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
CommonProgramFiles: 'C:\\Program Files\\Common Files',
PROMPT: '$P$G',
SESSIONNAME: 'Console',
COMPUTERNAME: 'MSI',
OneDriveConsumer: 'D:\\OneDrive',
__INTELLIJ_COMMAND_HISTFILE__:
'C:\\Users\\i\\.PhpStorm2019.1\\config\\terminal\\history\\history-34',
SystemDrive: 'C:',
NUMBER_OF_PROCESSORS: '12',
LOGONSERVER: '\\\\MSI',
TEMP: 'C:\\Users\\i\\AppData\\Local\\Temp',
TMP: 'C:\\Users\\i\\AppData\\Local\\Temp',
HOMEPATH: '\\Users\\i',
PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JSE;.WSF;.WSH;.MSC',
USERNAME: 'i',
ProgramFiles: 'C:\\Program Files',
USERDOMAIN_ROAMINGPROFILE: 'MSI',
LOCALAPPDATA: 'C:\\Users\\i\\AppData\\Local',
TERMINAL_EMULATOR: 'JetBrains-JediTerm',
PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 158 Stepping 10, GenuineIntel',
DriverData: 'C:\\Windows\\System32\\Drivers\\DriverData',
APPDATA: 'C:\\Users\\i\\AppData\\Roaming',
ALLUSERSPROFILE: 'C:\\ProgramData',
USERDOMAIN: 'MSI',
OS: 'Windows_NT',
PROCESSOR_LEVEL: '6',
ProgramData: 'C:\\ProgramData',
ComSpec: 'C:\\Windows\\system32\\cmd.exe',
PROCESSOR_ARCHITECTURE: 'AMD64',
FPS_BROWSER_USER_PROFILE_STRING: 'Default',
SystemRoot: 'C:\\Windows',
PROCESSOR_REVISION: '9e0a',
OneDrive: 'D:\\OneDrive',
PSModulePath:
'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules',
PATH:
'D:\\PhpStorm\\InHouseDevelopment\\my-library\\node_modules\\.bin;C:\\ProgramData\\DockerDesktop\\version-bin;C:\\Program Files\\Docker\\Docker\\Resources\\bin;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\iCLS\\;C:\\Program Files
\\Intel\\Intel(R) Management Engine Components\\iCLS\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Pro
gram Files\\Intel\\WiFi\\bin\\;C:\\Program Files\\Common Files\\Intel\\WirelessCommon\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\I
ntel(R) Management Engine Components\\IPT;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\Common Files\\Acronis\\VirtualFile\\;C:\\Program Files (x86)\\Common Files\\Acronis\\VirtualFile64\\;C:\\Program Files (x86)\\Com
mon Files\\Acronis\\FileProtector\\;C:\\Program Files (x86)\\Common Files\\Acronis\\FileProtector64\\;C:\\Program Files (x86)\\Common Files\\Acronis\\SnapAPI\\;C:\\Program Files\\nodejs\\;C:\\Program Files\\Git\\cmd;C:\\Program Files (x86)\\Yarn\\bin\\;C:\\Users\\t
okug\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\i\\AppData\\Roaming\\npm;C:\\Users\\i\\AppData\\Local\\Yarn\\bin;C:\\texlive\\2019\\bin\\win32',
'ProgramFiles(x86)': 'C:\\Program Files (x86)',
USERPROFILE: 'C:\\Users\\i',
windir: 'C:\\Windows',
ProgramW6432: 'C:\\Program Files',
configsetroot: 'C:\\Windows\\ConfigSetRoot',
'CommonProgramFiles(x86)': 'C:\\Program Files (x86)\\Common Files',
PUBLIC: 'C:\\Users\\Public',
HOMEDRIVE: 'C:',
CommonProgramW6432: 'C:\\Program Files\\Common Files' }
Trying to execute ChildProcess.spawn('env')
In Php Strorm console, it causes familiar Error: spawn env ENOENT.
As discussed in the chat, the error you are getting is usually caused by the fact that the executable you are trying to run is not available
Now there are multiple reasons the executable may not be available
The executable is not there at all anywhere on the system
The executable is there but not in the folders defined by system's PATH variable
The executable is there in the current directory but the directory context in which the process is being run is different
To fix #1 and #2 you just install the executable globally in system PATH
For fixing #3 you can do two things. Add the path for the current directory ({ cwd: __dirname}) and also a relative path to executable
const childProcess: ChildProcess__type = ChildProcess.spawn(
Path.resolve(__dirname, 'node_modules/.bin/electron'),
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ],
{ cwd: __dirname}
);
or
const childProcess: ChildProcess__type = ChildProcess.spawn(
'./node_modules/.bin/electron'),
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ],
{ cwd: __dirname}
);
or
const childProcess: ChildProcess__type = ChildProcess.spawn(
'node_modules/.bin/electron',
[ './ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname}
);
In case you decide to override the PATH environment variable you can do it passing the env parameters with more values
const childProcess: ChildProcess__type = ChildProcess.spawn(
'node_modules/.bin/electron',
[ './ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname, env: {....}}
);
You can use the existing environment variables from process.env and then update the same, and pass it to env parameter
it’s likely that you need to specify the full path to the electron command, since it isn’t on your path.
If you are running your script from your project root, electron is probably at in ./node_modules/.bin/electron, if they packaged up the app to be run that way.
I would guess that your alternative library checks node_modules by default.
The alternative would be to ensure electron is in your path, but that requires updating your system configuration, which it would be weird for a library to do.
Edit: example of call with path:
const childProcess: ChildProcess__type = ChildProcess.spawn(
'node_modules/.bin/electron',
[ 'ProjectInitializer__ElectronMain.js' ],
{ cwd: __dirname }
);
I'd also add some dumb logging on the process, so you know why the process failed:
function log(data) {
console.log("" + data)
}
child_process.stdout.on('data', log)
child_process.stderr.on('data', log)
child_process.on('close', log)

Codeanywhere Environment

I'm Using CodeAnywhere as my IDE and I wanted to use testing Environment not development.
how can I do that?
when I try Console.Log(process.env)
this comes out
{ MANPATH: '/home/cabox/.nvm/versions/node/v4.4.0/share/man:/usr/local/man:/usr/local/share/man:/usr/share/man',
TERM: 'xterm-256color',
SHELL: '/bin/bash',
SSH_CLIENT: '(Confidential)',
NVM_PATH: '/home/cabox/.nvm/versions/node/v4.4.0/lib/node',
OLDPWD: '/home/cabox/workspace',
SSH_TTY: '/dev/pts/0',
NVM_DIR: '/home/cabox/.nvm',
USER: 'cabox',
LS_COLORS: 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:o
w=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;3
1:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.ja
r=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.g
if=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*
.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;
35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01
;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;
36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00
;36:*.spx=00;36:*.xspf=00;36:',
MAIL: '/var/mail/cabox',
PATH: '/home/cabox/.nvm/versions/node/v4.4.0/bin:/home/cabox/.npm-packages/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/
usr/games',
NVM_NODEJS_ORG_MIRROR: 'https://nodejs.org/dist',
PWD: '/home/cabox/workspace/login-app',
SHLVL: '1',
HOME: '/home/cabox',
LOGNAME: 'cabox',
SSH_CONNECTION: '(Confidential)',
NVM_BIN: '/home/cabox/.nvm/versions/node/v4.4.0/bin',
LESSOPEN: '| /usr/bin/lesspipe %s',
NVM_IOJS_ORG_MIRROR: 'https://iojs.org/dist',
LESSCLOSE: '/usr/bin/lesspipe %s %s',
_: '/home/cabox/.nvm/versions/node/v4.4.0/bin/node' }
I if I can add some variables into this environment, then how can I do that?
if I want to create another Environment, then how can I do that?

spawnSync('npm', ['install']) gives [Error: spawnSync npm ENOENT]

I am having an issue with spawnSync is giving me ENOENT with simple "npm install". Can someone please help me?
======= NODE SCRIPT ==========
var child = require('child_process').spawnSync('npm', ['install']);
console.log(child.error);
===== OUTPUT ==========
[Error: spawnSync npm ENOENT]
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawnSync npm',
path: 'npm',
spawnargs: [ 'install' ]
only on windows but not on OS X.
This happens on
windows 7 x64
node version: 4.4.3
npm version: 2.15.1
I figured out the issue. On Windows, some commands need to be suffixed with .cmd in order to work. In this example, this updated command works for me:
require('child_process').spawnSync('npm.cmd', ['install']);
Or you can use cross-spawn to make it work cross-platform
I solved this by specifying the shell to be the v1 32-bit Powershell executable.
I don't know if there is a more reliable method of getting the Powershell executable path, but this is what I did:
const { spawnSync } = require('child_process')
const path = require('path')
const shell = process.platform === 'win32'
? 'C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe'
: undefined
const r0 = spawnSync('pnpm', ['run', 'build'], {
cwd: path.join(__dirname, '..', 'projects', 'project-name'),
env: process.env,
stdio: 'inherit',
shell
})
if (r0.error) {
console.log(r0.error)
process.exit(1)
}

Error importing Node.js modules into Intern tests

I'm trying out Intern for testing our Node.js modules. I've got it set up to run an empty test and even require node modules, but when I try to require one of the modules in our package I get the error:
/path/to/app/node_modules/path/path.js:327
var path = (i >= 0) ? arguments[i] : process.cwd();
^
TypeError: undefined is not a function
at Object.exports.resolve (/path/to/app/node_modules/path/path.js:327:52)
at Object.exports.relative (/path/to/app/node_modules/path/path.js:405:20)
at getSource (/path/to/app/node_modules/intern/lib/util.js:368:21)
at formatLine (/path/to/app/node_modules/intern/lib/util.js:405:40)
at processChromeTrace (/path/to/app/node_modules/intern/lib/util.js:418:16)
at normalizeStackTrace (/path/to/app/node_modules/intern/lib/util.js:470:38)
at Object.getErrorMessage (/path/to/app/node_modules/intern/lib/util.js:597:14)
at PreExecutor._handleError (/path/to/app/node_modules/intern/lib/executors/PreExecutor.js:256:24)
at /path/to/app/node_modules/intern/node_modules/dojo/lang.js:78:32
at process.<anonymous> (/path/to/app/node_modules/intern/lib/executors/PreExecutor.js:302:6)
Folder structure is:
src/
**/*.coffee
tests
unit/**/*.coffee
intern.js
js/ (coffeescript is compiled here)
src/
**/*.js
tests/
**/*.js
all.js (compiled by rolling up the names of the other tests under /js/tests)
node_modules
Here's my intern.js:
define({
capabilities: {
'browserstack.selenium_version': '2.45.0'
},
environments: [
{browserName: 'internet explorer', version: '11', platform: 'WIN8'},
{browserName: 'internet explorer', version: '10', platform: 'WIN8'},
{browserName: 'internet explorer', version: '9', platform: 'WINDOWS'},
{browserName: 'firefox', version: '37', platform: ['WINDOWS', 'MAC']},
{browserName: 'chrome', version: '39', platform: ['WINDOWS', 'MAC']},
{browserName: 'safari', version: '8', platform: 'MAC'}
],
maxConcurrency: 2,
tunnel: 'BrowserStackTunnel',
loaderOptions: {
packages: [{name: 'app', location: 'js/src'}]
},
reporters: ['Console', 'Lcov'],
suites: ['js/tests/unit/all'],
excludeInstrumentation: /^(?:\.npm|js\/tests|src|tests|node_modules)\//
});
My test is just:
define (require) ->
registerSuite = require('intern!object')
assert = require('intern/chai!assert')
SchemaBuilder = require('intern/dojo/node!app/path/to/Module')
registerSuite
name: 'Testing'
'test': ->
From the project root I'm running './node_modules/.bin/intern-client config=tests/intern'
Is this a problem with my code, configuration, environment, or Intern?
I've tried with Node.js v0.12.0 and v0.12.7.
Interestingly, removing the path module from my app dependencies (package.json) resolved (well, avoided) the undefined is not a function error, seemingly falling back on Intern's own path resolution. I don't really know why, but this seems like a bug.
This presented a new, more tractable error: Error: Cannot find module 'app/path/to/Module', suggesting the path in the require() was simply wrong.
I think the problem is that the intern/dojo/node loader doesn't support the loaderOptions: {packages: [{name: 'app', location: 'js/src'}]} configuration, and hence it is searching for an app directory relative to the test module. If I replace app/ with ../../../../js/src/ then it resolves and works as expected.
It's a bit ugly, but it's the standard way of requiring local files in node, so it's also not too surprising, I had just hoped Intern's loader could make it cleaner.

Resources