I'm trying to convert a web application into an electron app. I have multiple functions, in different files that I've imported into my main.js using a transpiler.
However, whenever I try do that in my electron app, I run into an issue with a module I'm using to move away from using php to access my database. Instead I'm using the mysql module on npm.
I want to save this function in its own file, and then require it in main.js. When I try to transpile it with babel, I get an error about Net.Connection not working (or something along those lines). As I understand it, this is because of how Node works. I'm happy to work around this, but I'm hoping there's a way to save this function in another file, and import it without having to use babel.
function loadColourFilter(){
var mysql = require('mysql');
let query_result;
var connection = mysql.createConnection({
host : 'xxxxxxxxxxxx',
user : 'xxxxxxxxxxxx',
password : 'xxxxxxxxxxxx',
database : 'xxxxxxxxxxxx'
});
connection.connect();
let query = "xxxxxxxxxxxxxxxx";
connection.query(query, function (error, results, fields) {
});
connection.end();
return (query_result);
}
EDIT: I've removed some parts of the function to keep credentials safe and whatnot. I'm fairly certain their absence won't change anything when trying to solve this.
EDIT:
My project directory is essentially
src
--- js
--- --- main.js
--- functionFile.js // This would be where my loadColourFilter function above would be saved
--- node_modules
--- --- ...
--- index.html // js/main.js is referenced in a script tag here.
--- main.js // Where the electron window is created.
--- package.json
There should be 2 js contexts, one running in the electron app and one running in node. You won't be able to require you scripts directly from your directory if you are in the electron context (which is like a browser js context).
I'm just assuming this is the case since we don't get a lot of information for your problem, and the other answer should have resolved your problem.
Try to include your js file in your index.html and see what's up.
Edit: Since it's a Transpiling error with babel, babel is probably transpiling for node when it should transpile for the browser.
You can easily make a simple local module using NodeJS by creating a source file and then adding a module.exports assignment to export some functionality/variables/etc from the file. In your case something like a file named colourFilter.js with the contents:
function load(){
var mysql = require('mysql');
let query_result;
var connection = mysql.createConnection({
host : 'xxxxxxxxxxxx',
user : 'xxxxxxxxxxxx',
password : 'xxxxxxxxxxxx',
database : 'xxxxxxxxxxxx'
});
connection.connect();
let query = "xxxxxxxxxxxxxxxx";
connection.query(query, function (error, results, fields) {
});
connection.end();
return (query_result);
}
module.exports = load
And then in your code where you'd like to use it include it by doing something like:
loadColourFilter = require('colourFilter.js')
And use the function like
let result = loadColourFilter()
This is a simple way to split up your code into multiple files/classes/modules but still keep one main file/class/module as the important one which is the public-facing portion or entry point. And of course you don't have to use the names I've used above :P
If you would like to make an object-style module you can instead export an object like
module.exports = {
load
}
Or
module.exports = {
load: loadFunctionNameInThisFile
}
And then use it like
const colourFilter = require('colourFilter.js')
let result = colourFilter.load()
Related
I have added a js Module called mongoUtil, which contains the code hereafter, following a suggestion found at this link.
const MongoClient = require( 'mongodb' ).MongoClient;
const url = "mongodb://localhost:27017";
var _db;
module.exports = {
connectToServer: function(callback) {
MongoClient.connect(url, {useNewUrlParser: true}, function(err, client) {
_db = client.db('MyDB');
return callback(err);
});
},
getDb: function() {
return _db;
}
};
I have furthermore used the following line in my app.js Module:
const mongoUtil = require('mongoUtil')
However, I am obtaining the following error while the 2 Modules are located in the same Directory:
Error: Cannot find module 'mongoUtil'
What am I missing?
If you provide a module name to require it will search node_modules for it.
If you want to read a module from the current directory, you need to use the file path. This can be relative: require("./mongoUtil")
The exact documentation is here including a (rather long) pseudocode explanation of how the algorithm of locating a module works.
But in short, there are two basic ways of loading a module:
Using the name of an installed module (may be globally or locally installed), for example require('mongodb'). This would look for the (global or local) node_modules/mongodb folder.
Using a path (absolute or relative), for example require('./mongoUtil'). This would look for a file at the given path - if it's relative, then it is relative to the current file.
So, the solution is to use require('./mongoUtil') and not require('mongoUtil').
This will work:
const mongoUtil = require('./mongoUtil.js');
Or even just the following, since the extension is automatically resolved:
const mongoUtil = require('./mongoUtil');
I'm writing a shell script, and would like to use template it, by keeping my variables in a json file.
I'm a beginner to javascript, and so can't seem to get the hang of how to use nunjucks to render my templates. Can you please help me get this simple example to work?
Here's my current attempt. (I have npm installed)
In my project directory :
$ npm install nunjucks
I create sample.njk with the following contents :
{{ data }}
And index.js with the following content :
var nunjucks = require('nunjucks')
nunjucks.configure({ autoescape: true });
nunjucks.render('sample.njk', { data: 'James' });
My project directory then, looks like :
index.js node_modules/ sample.njk
I run index.js with node as
$ node index.js
How do I get it to output (to the command line, or to a new file):
James
after processing the template?
I've tried looking at gulp-nunjucks and gulp-nujucks-render, but there's too much going on there, and I can't even get a simple task accomplished here.
When I define my data in a json file, I only need pass it as a context in the nunjucks.render() function, right?
Thanks for your help.
Depends on what you're trying to accomplish with the data outputted by the Nunj render. If you simply want to print it to the terminal, a simple console.log(); will work.
In Express, res.render takes an optional third param which is a fn. You would do it as such:
var nunjucks = require('nunjucks');
nunjucks.configure({ autoescape: true });
nunjucks.render('sample.njk', { data: 'James' }, function (err, output) {
// If there's an error during rendering, early return w/o further processing
if (err) {
return;
}
// The render fn calls the passed-in fn with output as a string
// You can do whatever you'd like with that string here
console.log(output);
});
I'm currently learning Node.js and I'm having trouble integrating constants into my service. I have created a constants file and am referencing those values from other files. Unfortunately, I don't seem to be doing it correctly as things start to fail when I reference constants rather than just place literals into all of my function calls.
constants.js
exports.DB_HOST = 'localhost';
exports.DB_PORT = 3306;
exports.DB_USER = 'user';
exports.DB_PASSWORD = 'password';
exports.DB_DATABASE = 'database';
When trying to connect to a MySQL database, the connection fails as the server claims that the credentials are incorrect. However, when I replace all of the constants below with literals, everything works correctly (so I'm not using incorrect authentication information).
var constants = require('constants');
...
var connection = mysql.createConnection({
host: constants.DB_HOST,
port: constants.DB_PORT,
user: constants.DB_USER,
password: constants.DB_PASSWORD,
database: constants.DB_DATABASE
});
...
connection.query('SELECT * FROM table',
function(err, rows, fields) {
res.send(err);
});
constants is a built-in node module that provides system-level constants for use with other built-in modules, like fs, crypto, etc. If you want your constants.js, you will need to include the (absolute or relative) path to it. For example:
var constants = require('./constants');
In addition to changing your require() to use your local module rather than a built-in module:
var constants = require('./constants');
There is a misspelling here in your code:
port: constants.DB_POST,
// wrong character ^
should be:
port: constants.DB_PORT,
So, a couple things:
It looks like you're trying to require either an installed node module called constants or a built-in module (which is pretty much a set of constants for us in built-in node modules like fs, http, crypto, etc.). That would be the main reason you can't access it. Node doesn't know to look for your local module b/c no path string has been supplied.
you might be able to clean up your module a bit w/ some optional but (sometimes) helpful refactoring.
I would recommend the following change to how you require your module:
// Bc it's a set of constants, use the es6/2015 `const` if available when requiring your module
const constants = require('./constants');
You could clean up your module a little bit w/ module.exports; makes it really clear what the object you're exposing is:
module.exports = {
DB_HOST : 'localhost',
DB_PORT : 3306,
DB_USER : 'user',
DB_PASSWORD : 'password',
DB_DATABASE : 'database',
}
Another consideration: in most apps, you really want to keep configuration as internally-stateless as possible. That means your app shouldn't really have any configurational values hard-coded into it. Generally, if you avoid doing so you will have a much more flexible setup externally. In other words, you'd be able to spin up as many different instances as you want with as many different databases to connect to. When you change databases, you'd only have to change the environment, not the app itself. And, if you get into the semantics of it all, your app's job is to connect, not to really decide where to connect — the environment should provide that. So, these could be made available from your module as:
const config = {
DB_HOST : process.env.DB_HOST,
DB_PORT : process.env.DB_PORT,
DB_USER : process.env.DB_USER,
DB_PASSWORD : process.env.DB_PASSWORD,
DB_DATABASE : process.env.DB_DATABASE,
};
module.exports = config;
You could just access them from anywhere with process.env.YOUR_VAR, but if you want to consolidate them all in a module that is just as good in many ways and would let you change external config value variable names (i.e. process.env.DB_USERNAME instead of DB_USER) and not have to change it everywhere else (if you don't need the names to be kept in sync).
Hope that helps! :)
I am trying to search the best approach to manage different values for same variables in Devlopment, Test and Production environment.
For example, I have variable jsonFile which can be:
var jsonFile = http://localhost:63342/json/appsconfig.json
for development env
var jsonFile = http://192.168.35.59/applications/json/appsconfig.json
for test env
var jsonFile = http://example.com/applications/json/appsconfig.json
for production env
I am trying to read a lot about Frontend Development Stack, but I am confused about what tool to use. I will use Google Closure Tools for minification, can it be also useful to switch variable values? Or can it be considered a Grunt task (even if I am not able to understand how to properly configure Grunt tasks...)?
What might be better is to write the JSON into a JS file that is part of your build artifacts. Something like file-creator that can write a file like so (using a simplistic setup that can obviously be made more dynamic).
In the top of your module.exports for grunt tasks, load in the config file into a var like:
var configData = grunt.file.readJSON('../config/appsconfig.json'),
Then write to a new JS file using the grunt file-creator module
"file-creator": {
'dev': {
'build/config.js': function (fs, fd, done) {
fs.writeSync(fd,
'var yourSiteHere = yourSiteHere || {}; yourSiteHere.config = '
+ JSON.stringify(configData) + ";"
);
done();
}
}
}
Then load this JS file into the page (perhaps even minify it using a separate grunt task). You will be then able to refer to the config data like so:
var apiEndPoint = yourSiteHere.config.api.apiEndPoint,
apiKey = yourSiteHere.config.api.apiKey;
I am aware I can create a custom file inside the config directory and reference the variables from within that
module.exports.myconfig = {
foo: 'bar'
}
sails.config.myconfig.foo
But I need to write to these variables too and have them saved. In previous projects I have done this with JSON config files and used PHP to write to them.
Is there any way of doing this with Sails or should I just create some JSON files to pull and push my config vars?
There's no mechanism built in to Sails for persisting configuration variables. However, in the latest build of Sails there is a lower event you can listen for which indicates that Sails is exiting. You could catch this and persist your data then. For example, in your /config/bootstrap.js, something like:
var fs = require('fs');
module.exports = function(cb) {
sails.on('lower', function persistConfig() {
fs.writeFileSync(sails.appPath+'/config/myConfig.js',
'module.exports = ' + JSON.stringify(sails.config.myconfig));
});
// ... other bootstrap stuff ...
return cb();
}