SailsJS how to specify file paths at the root level of project - node.js

I got a SailsJS application in which I need to reference a htpasswd file that is located at the root of my project:
var auth = require('http-auth');
var basic = auth.basic({
authRealm: "Admin Panel",
authFile: 'htpasswd', // <-- how do I specify the path to this file ?
authType: 'basic'
});
module.exports = function(req, res, next) {
basic.apply(req, res, function(username) {
if(!username) {
return res.serverError(403, 'You are not authorized');
}
next();
})(req, res);
}
I have tried using:
authFile: '/htpasswd'
As well as:
authFile: '~/htpasswd'
Neither works.
Update
Hurmm....it seems like it's not the code that has error, somehow, my Sailsjs application can't find the htpasswd module.
I did do:
sudo npm install -g htpasswd
I also used htpasswd command line to generate the htpasswd file...somethings wrong with my project setup...
My console error says:
Error: Cannot find module 'htpasswd'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/MacUser/SailsProjects/SecurePanel/node_modules/http-auth/gensrc/auth/basic.js:11:14)

Use the native __dirname variable which evaluates to the path of the current file.
See what it is using console.log(__dirname). And then you could do:
var basic = auth.basic({
realm: "Admin Panel",
file: __dirname + "/path_from_current_file_to/htpasswd"
});
So if the root was a folder up from this the folder that this script is in, you could do
__dirname + "/../htpasswd"

Related

.env file not being recognized when trying to read from a file within a folder instead of root in NodeJS

In my NodeJS app, I have .env file in root directory with following info:
NODE_ENV = development
PORT = 3002
#db credentials
dbURL = 'mongodb+srv://username:password#clusterName-0gcm3.mongodb.net/dbName?retryWrites=true&w=majority'
And in the root directory I also have config file (config.js) which grabs the variables:
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
port: process.env.PORT,
dbURL: process.env.dbURL
}
In my App.js which is again in root folder I am able to successfully read this file and able to connect with DB:
const express = require('express');
const mongoose = require('mongoose');
const { port, dbURL } = require('./config'); //reading the config file and grabbing the vars
const app = express();
app.use(express.json());
//works well!
mongoose.connect(dbURL, { useUnifiedTopology: true, useNewUrlParser: true})
.then(res => {
console.log(`Listening on port ${port}`);
app.listen(port);
})
.catch(err => console.error(err));
Now I am trying to write some standalone scripts to populate the DB with some sample data and in that script I am trying to connect to DB seperately as those scripts will only be executed with node <file> command. This file (dbPopulate.js) is located within /helper-scripts/ folder. And the script looks like this:
const express = require('express');
const mongoose = require('mongoose');
const {port, dbURL} = require('../config'); //attempting to read config.js that calls the .env file
const app = express();
app.use(express.json());
console.log(dbURL, port) //throws undefined for both vars
mongoose.connect(dbURL, { useUnifiedTopology: true, useNewUrlParser: true})
.then(res => {
console.log(`Listening on port ${port}`);
app.listen(port);
})
.catch(err => console.error(err));
Just to make it clear this is my file structure:
/.env
/app.js
/config.js
/helper-scripts/dbPopulate.js (culprit)
UPDATE for displaying error log:
When I execute dbPopulate.js standalone I get following errors:
$ node dbPopulate.js
undefined undefined
C:\teamSIO\server\node_modules\mongoose\lib\connection.js:582
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at NativeConnection.Connection.openUri (C:\teamSIO\server\node_modules\mongoose\lib\connection.js:582:11)
at Mongoose.connect (C:\teamSIO\server\node_modules\mongoose\lib\index.js:335:15)
at Object.<anonymous> (C:\teamSIO\server\helper-scripts\dbPopulate.js:30:10)
at Module._compile (internal/modules/cjs/loader.js:1123:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
at Module.load (internal/modules/cjs/loader.js:972:32)
at Function.Module._load (internal/modules/cjs/loader.js:872:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
I would try using an array instead of an object.
require('dotenv').config();
const port = process.env.PORT;
dbURL: process.env.dbURL;
module.exports = [
port,
dbURL
];
and to use
const [port, dbURL] = require('./config');
Also, I don't think that this was the error, but you do have two dots in your "dbPopulate.js" const {port, dbURL} = require('../config'); file, this might be your problem
It's been a long time since you asked, but maybe my answer will help someone else.
When you execute node dbPopulate.js from directory helper-scripts the function require will be able to correctly load ../config, but that in turn will fail to find the file .env because it expects to find it at the same level, from a file/directory hierarchy perspective.
You can either copy .env inside helper-scripts, which you'd better not, or execute dbPopulate.js from project's root directory.
when u run a node app where the .env file is not in the same relative location as the file u are running then u need to specify the correct path for the .env file.
Example if i have app.js and .env file both inside the same project folder location then when I'll do node app.js, then just dotenv.config() will work fine as its default path is
process.cwd() + '.env'
but for say i have a file inside seeder/chat-message-type.seeder.js then to read the .env file which is outside i have to go out one directory.
const path = require("path")
// have to modify dotenv file path becuase the app is run from seeder folder
dotenv.config({ path: path.join(process.cwd(), "..", ".env") })
This will ensure that whenever i am reading the .env file by running
cd seeder
node chat-message-type.seeder.js
it will still load all the data from .env file.

why cloud funtion in node js doesnt deploy propely

here iam using a cloud functions to create users i am using a express module when i try to deploy this code it deploying to cloud funtions with message that Error : Funtions did not deploy properly
const express = require('express');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const serviceaccount = require('./ServiceAccountKey.json');
const app = express();
admin.initializeApp({
credential: admin.credential.cert(serviceaccount)
});
app.post('/',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
when i add this at end
module.exports = {
app
}
it showing funtion deployed but its not showing in cloud functions dashboard
what wrong am i doing here
here is the error what ima getting i cnat get whAT THE error is
⚠ functions[register(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:476:15)
at Function.Module._load (module.js:424:25)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:1:79)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
Functions deploy had errors with the following functions:
register
You code never uses the firebase-functions modules to declare a Cloud Function. Your functions variable is going unused. You can't just export any function an expect it to run - it has to be built by the SDK.
If you have an express app to deploy, you need to export it via an HTTP type function:
exports.app = functions.https.onRequest(app);
First, I think you need to change the endpoint of the url. Don't just put '/'. Maybe like '/user/create'.
app.post('/user/create',(req,res)=>{
if(req.method!== 'POST'){
res.status(400).send("what are u trying baby");
return;
}
admin.auth().createUser({
email:req.body.email,
password: req.body.pass,
}).then(function(userRecord){
res.send({'uid': userRecord.uid});
return;
}).catch(function(error){
res.send({'error': 'Try COrrect one baby'});
return;
});
return;
});
exports.register = funtions.Https.onRequest(app);
And in your firebase.json you should rewrite the url :
{
"functions": {
...
},
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/user/create",
"function": "register"
}
]
}
}
For more explanation, you can follow this tutorial.

Node.js Module not found

I am experience a Module Not Found error for an NPM package that is installed and appears to be present in the node_modules folder. Is something missing in the underlying package itself?
Here is my package.json:
{
"name": "cmtest",
"version": "0.0.0",
"description": "cmtest",
"main": "server.js",
"author": {
"name": "Andrew"
},
"dependencies": {
"cloudmersive": "^1.3.2"
}
}
And then I am calling a require:
'use strict';
var http = require('http');
var Cloudmersive = require('cloudmersive');
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
var api = new Cloudmersive.BarcodeLookupApi()
var value = "value_example"; // {String} Barcode value
var callback = function (error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
api.barcodeLookupEanLookup(value, callback);
}).listen(port);
But I am getting this error:
"Cannot find module 'cloudmersive'"
"Error: Cannot find module 'cloudmersive'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
at Function.Module._load (internal/modules/cjs/loader.js:497:25)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (c:\users\andrew\documents\visual studio 2017\Projects\cmtest\cmtest\server.js:3:20)
at Module._compile (internal/modules/cjs/loader.js:675:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)"
Any ideas? Is there something wrong with the package itself? Is it a development/configuration issue on my part?
The package cloudmersive is installed with NPM and shows up in the node_modules folder. I also tried using nvm to switch between several different versions.
Underlying package source is here: https://github.com/Cloudmersive/Cloudmersive.APIClient.Javascript
Is there something wrong with the index.js file?
package.json for cloudmersive says main is src/client.invoker/index.js but the file is not in that directory.
To use the library locally without publishing to a remote npm registry, first install the dependencies by changing
into the directory containing package.json. Let’s call this JAVASCRIPT_CLIENT_DIR. Then run:
npm install
Next, link it globally in npm with the following, also from JAVASCRIPT_CLIENT_DIR:
npm link
Finally, switch to the directory you want to use your cloudmersive from, and run:
npm link /path/to/<JAVASCRIPT_CLIENT_DIR>
You should now be able to require('cloudmersive') in javascript files from the directory you ran the last
command above from.
You can checkout the README.md file inside the cloudmersive module which you have installed inside your node_modules directory to get more detailed instructions on this.

webpack exception when using express middleware router

I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
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/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5

ReferenceError: describe is not defined NodeJs

I am trying to define some endpoints and do a test using nodejs. In server.js I have:
var express = require('express');
var func1 = require('./func1.js');
var port = 8080;
var server = express();
server.configure(function(){
server.use(express.bodyParser());
});
server.post('/testend/', func1.testend);
and in func1.js:
var testend = function(req, res) {
serialPort.write("1", function(err, results) {
serialPort.write("2" + "\n", function(err, results) {
});
});
});
exports.testend = testend;
Now in test.js I am trying to use this endpoint:
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var http = require('http');
var app = require('./../server.js');
var port = 8080;
describe('Account', function() {
var url = "http://localhost:" + port.toString();
it('test starts', function(done) {
request(url).post('/testend/')
// end handles the response
.end(function(err, res) {
if (err) {
throw err;
}
res.body.error.should.type('string');
done();
});
});
});
But when I run node test.js I am getting this error:
describe('Account', function() {
^
ReferenceError: describe is not defined
at Object. (/test/test.js:9:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
How can I fix the issue?
Assuming you are testing via mocha, you have to run your tests using the mocha command instead of the node executable.
So if you haven't already, make sure you do npm install mocha -g. Then just run mocha in your project's root directory.
if you are using vscode, want to debug your files
I used tdd before, it throw ReferenceError: describe is not defined
But, when I use bdd, it works!
waste half day to solve it....
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",// set to bdd, not tdd
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test/**/*.js"
],
"internalConsoleOptions": "openOnSessionStart"
},
To run tests with node/npm without installing Mocha globally, you can do this:
• Install Mocha locally to your project (npm install mocha --save-dev)
• Optionally install an assertion library (npm install chai --save-dev)
• In your package.json, add a section for scripts and target the mocha binary
"scripts": {
"test": "node ./node_modules/mocha/bin/mocha"
}
• Put your spec files in a directory named /test in your root directory
• In your spec files, import the assertion library
var expect = require('chai').expect;
• You don't need to import mocha, run mocha.setup, or call mocha.run()
• Then run the script from your project root:
npm test
You can also do like this:
var mocha = require('mocha')
var describe = mocha.describe
var it = mocha.it
var assert = require('chai').assert
describe('#indexOf()', function() {
it('should return -1 when not present', function() {
assert.equal([1,2,3].indexOf(4), -1)
})
})
Reference: http://mochajs.org/#require
i have this error when using "--ui tdd".
remove this or using "--ui bdd" fix problem.
OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically
This is what injected describe and it into my tests.
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
I tried tdd like in the docs, but that didn't work, bdd worked though.
for Jest you have to add "jest": true to .eslintrc
{
"env": {
"browser": true,
"es6": true,
"jest": true
},
...
Make sure you have a folder named as test that contains your test.js file.
Also make sure you have mocha available in your project by running mocha -version in terminal (at project path)
Make sure your project has package.json available, if not run npm init -y
And finally to run mocha test scripts, on terminal (on project path) run npm test

Resources