Why am I getting Error: Configuration property “jwtPrivateKey” is not defined? - node.js

I keep getting this error message when I run my index.js file via NodeJS terminal. My editor is VS Code. I am on Windows.
I loaded npm config module into my index.js file. I created a custom-environment-variables.json. I set my password, vidlyPrivateKey, in my Node Terminal. I don't know why this is happening. Any help would be much appreciated!
Here is my index.js code:
const config = require('config');
try {
const myKey = config.get("jwtPrivateKey");
debug(myKey);
} catch (error) {
debug(error, "FATAL ERROR: jwtPrivateKey is not defined.");
return process.exit(1);
}
custom-environment-variables.json:
{
"jwtPrivateKey": "vidlyPrivateKey"
}

It is because the naming of the file, it should be inside a config folder and be name as default.json , config/default.json
These are the documentation https://www.npmjs.com/package/config.

Related

Couldn't compile opencv4nodejs in Vue + electron application

I am trying to build a face detection application with opencv4nodejs, vue + electron-builder. During the process of application setup I cam across a problem where I get the following error during npm run serve after installing opencv4nodejs.
Failed to compile.
./node_modules/opencv4nodejs/build/Release/opencv4nodejs.node 1:2
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
It would be great if some one can help me with it. Thank you in advance
Update: I have added my view.config.js for reference
module.exports = {
chainWebpack: config => {
config.module;
// add ts files
// .rule('ts')
// .use('ts-loader')
// .loader('ts-loader')
// .tap(options => {
// modify the options...
// return options
// })
}
};
As our friend #Eldar commented adding node-loader to vue.config.js works for me. Thank you
module.exports = {
chainWebpack: config => {
config.module .rule('ts')
.use('ts-loader')
.loader('ts-loader')
.end()
.rule(/\.node$/)
.use('node-loader')
.loader('node-loader')
.end()
}
};
Hope this is useful folks.

typescript cannot recognize .sequelizerc file

I have this .sequelizerc file:
const path = require('path');
module.exports = {
config: path.resolve('.', 'src/config/sequelizeCLIConfig.json'),
'migrations-path': path.resolve('.', 'db', 'migrations'),
};
And then I have a .ts file that generates the cli config file named generateSequelizeCLIConfig.ts, which does the following thing:
import path from 'path';
import fs from 'fs';
import config from '../../src/config';
import sequelizeRC from '../../.sequelizerc';
const env = process.env.NODE_ENV || 'development';
const targetFile = path.resolve(sequelizeRC.config);
const sequelizeCLIConfig: Record<string, any> = {};
sequelizeCLIConfig[env] = config.db;
fs.writeFile(targetFile, JSON.stringify(sequelizeCLIConfig, null, 4), err => {
if (err) {
return console.log(err);
}
console.log('The sequelizeCLI config file was saved at ' + targetFile + '!');
});
The plan is, every time I need migration, I run this script first. This script grabs the data from the config folder and generate the src/config/sequelizeCLIConfig.json. And then I run the migration with config data from this .json file.
So the file structure is this:
-.sequelizerc
-db
|-scripts
|-generateSequelizeCLIConfig.ts
-src
|-config
|-index.ts
.sequelizerc
However I got this error when compiling generateSequelizeCLIConfig.ts:
TSError: ⨯ Unable to compile TypeScript:
db/scripts/generateSequelizeCLIConfig.ts(4,25): error TS2307: Cannot find module '../../.sequelizerc'.
So it seems .sequrlizerc is not recognized although I have double checked that this file does exist.
My guess is, .sequelizerc behind the scene is a .js file, not a .ts file, and this gives me some trouble. But I don't know how to verify this, nor how to fix it.
Any suggestions?
Try to add the .sequelizerc to your include in your tsconfig as follows:
{
..prev configs...,
include: [ ...your paths..., ".sequelizerc"],
}
Delete dot. Rename the .sequelizerc to sequelizerc

fs.writeFileSync function doesn't write to file when included as a module

Consider the following:
conversations.json : []
db.js :
let fs = require('fs');
let conversations = require('./conversations.json');
function addConversation(conversation){
console.log(conversations);
conversations.push(conversation);
try{
fs.writeFileSync('conversations.json', JSON.stringify(conversations));
}
catch(err){
console.error('Parse/WriteFile Error', err)
}
}
module.exports = {
addConversation
}
app.js :
let database = require('./db.js');
database.addConversation(
{
key1: '1233',
key2: '433',
key3: '33211'
}
);
Running:
node app.js
No error is being raised. Everything compiled as expected. The problem is that the conversations.json isn't being updated once the addConversation function is called from app.js.
What's interesting is that once the addConversation is called within the db.js everything works great and the conversations.json is being updated.
What am I missing?
What am I missing?
Probably when loading as a module, you're writing the file to the wrong directory.
When you do this:
fs.writeFileSync('conversations.json', JSON.stringify(conversations));
That writes conversations.json to the current working directory which may or may not be your module directory. If you want it written to your module directory which is where this:
let conversations = require('./conversations.json');
will read it from, then you need to use __dirname to manufacture the appropriate path.
fs.writeFileSync(path.join(__dirname, 'conversations.json'), JSON.stringify(conversations));
require() automatically looks in the current module's directory when you use ./filename, but fs.writeFileSync() uses the current working directory, not your module's directory.

Copy file and replace variable with NodeJS

I try to copy and replace some variable in multiples files. For this, i use esj module replace my vars.
But i don't know if ejs module is correct for my case. I would like just copy "template" initial file and replace variable in file.
My exemple using NodeJS :
const symfonyPluginPath = path.join(
__dirname,
'../plugins/symfony/template'
);
const testPath = path.join(__dirname, '../plugins/test');
shell.rm('-rf', testPath);
shell.mkdir(testPath);
shell.cp('-r', `${symfonyPluginPath}/*`, testPath);
shell.cp('-r', `${symfonyPluginPath}/.*`, testPath);
shell.cd(testPath);
// #ts-ignore
fs.readdir(testPath, (error, files) => {
files.forEach((file) => {
const compiled = ejs.compile(
fs.readFileSync(`${testPath}/${file}`, 'utf8')
);
const test = compiled({ appName: 'test' });
console.log(test);
});
});
This code work for only 1 file, but in forEach i've an error EISDIR: illegal operation on a directory, read.
I don't know if my approch is good and if ejs is the correct module for this.
Anyone can help me ?
Thank you community !
EISDIR stands for "Error, Is Directory". This means that NPM is trying to do something to a file but it is a directory.
Try in this format ---
path.join('x/y/z', '/plugins/test')

reading a packaged file in aws lambda package

I have a very simple node lambda function which reads the contents of packaged file in it. I upload the code as zip file. The directory structure is as follows.
index.js
readme.txt
Then have in my index.js file:
fs.readFile('/var/task/readme.txt', function (err, data) {
if (err) throw err;
});
I keep getting the following error NOENT: no such file or directory, open '/var/task/readme.txt'.
I tried ./readme.txt also.
What am I missing ?
Try this, it works for me:
'use strict'
let fs = require("fs");
let path = require("path");
exports.handler = (event, context, callback) => {
// To debug your problem
console.log(path.resolve("./readme.txt"));
// Solution is to use absolute path using `__dirname`
fs.readFile(__dirname +'/readme.txt', function (err, data) {
if (err) throw err;
});
};
to debug why your code is not working, add below link in your handler
console.log(path.resolve("./readme.txt"));
On AWS Lambda node process might be running from some other folder and it looks for readme.txt file from that folder as you have provided relative path, solution is to use absolute path.
What worked for me was the comment by Vadorrequest to use process.env.LAMBDA_TASK_ROOT. I wrote a function to get a template file in a /templates directory when I'm running it locally on my machine with __dirname or with the process.env.LAMBDA_TASK_ROOT variable when running on Lambda:
function loadTemplateFile(templateName) {
const fileName = `./templates/${templateName}`
let resolved
if (process.env.LAMBDA_TASK_ROOT) {
resolved = path.resolve(process.env.LAMBDA_TASK_ROOT, fileName)
} else {
resolved = path.resolve(__dirname, fileName)
}
console.log(`Loading template at: ${resolved}`)
try {
const data = fs.readFileSync(resolved, 'utf8')
return data
} catch (error) {
const message = `Could not load template at: ${resolved}, error: ${JSON.stringify(error, null, 2)}`
console.error(message)
throw new Error(message)
}
}
This is an oldish question but comes up first when attempting to sort out whats going on with file paths on Lambda.
Additional Steps for Serverless Framework
For anyone using Serverless framework to deploy (which probably uses webpack to build) you will also need to add the following to your webpack config file (just after target: node):
// assume target: 'node', is here
node: {
__dirname: false,
},
Without this piece using __dirname with Serverless will STILL not get you the desired absolute directory path.
I went through this using serverless framework and it really was the file that was not sent in the compression. Just add the following line in serverless.yml:
package:
individually: false
include:
- src/**
const filepath = path.resolve('../../filename.text');
const fileData2 = fs.readFileSync(process.env.LAMBDA_TASK_ROOT + filepath, 'utf-8');
I was using fs.promises.readFile(). Couldn't get it to error out at out. The file was there, and LAMBDA_TASK_ROOT seemed right to me as well. After I changed to fs.readFileSync(), it worked.
I hade the same problem and I tried applying all these wonderful solutions above - which didn't work.
The problem was that I setup one of the folder name with one letter in upper case which was really lowercase.
So when I tried to fetch the content of /src/SOmething/some_file.txt
While the folder was really /src/Something/ - I got this error...
Windows (local environment) is case insensitive while AWS is not!!!....

Resources