How to call function from other local file Node.js? - javascript

I tried like this from main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const parser = require('./parser.js');
parser.parseHash(url)
But got error that: parser.parseHash is not function
// parser.js file
function parseHash(url) {
...
}

Are you exporting parseHash function in parser.js file?
module.exports = {
parseHash,
}

// parser.js
exports.parseHash = function (url) {
...
};
//main.js
const parseHash = require('./parser').parseHash;
parseHash(url)

You need to export the function like this:
// parser.js file
function parseHash(url) {
...
}
module.exports = {
parseHash: parseHash
}

Related

electron "MAIN" : requiring you own js file and call function from it

I'm can't understand some things here related to electron. I've been searching for hours for the magic answer but couldn't find anything.
My goal is simple. I don't want my main electron.js file to be 5000 lines long without any kind of organization so I'm trying to split the code into multiple js file that make sense.
My idea was to use import { someFunction1, someFunction2 } from './scripts/someScript' in my electron.js and then just creating that file with the arrow function in it and export them.
Then I could call the function as I want in the main file. However, it doesn't seem to be possible. I've read electronjs doesn't support ES6 syntax. I've read about Babel (But from what I read, it implies a bunch of additional configuration and I don't want to spend days trying to add this to the bunch of configuration that are already messy with electron + React (No boiler plate here). And I didn't find anything specifics for this combo.
Question is. Is this doable in 2021? Am I missing anything? What would you guys recommend?
File would look something like this:
import { someNodeModuleFunction } from 'someNodeModule';
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
export { someFunction1, someFunction2 }
EDIT
Here's the actual code I have a problem with. I still get
if the file is .js: "Must use import to load ES Module"
If the file is .mjs: "Cannot use import statement outside a module"
This script is simply using fs to create a directory:
DataManagement.mjs:
import { existsSync, mkdir } from 'fs';
const electron = require('electron');
const app = electron.app;
const documentFolder = app.getPath('documents');
const CreateDataDirectory = () => {
const mainPath = documentFolder + 'AppName'
if (!existsSync(mainPath)) {
mkdir(mainPath);
}
};
module.exports = { CreateDataDirectory }
Calling it like that in electron.js:
const { CreateDataDirectory } = require('./scripts/DataManagement.mjs');
[...]
CreateDataDirectory()
Not sure how dividing the code can be that hard. :)
You may need to use Node.js module syntax (require and module.exports) or Babel (code transpiler).
For example:
import { someNodeModuleFunction } from 'someNodeModule';
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
module.exports = { someFunction1, someFunction2 }
Using your module:
const { someFunction1, someFunction2 } = require ('./FILE.js');
// ...
You could use module.exports:
otherModule.js
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
module.exports = {
someFunction1,
someFunction2
};
main.js
const { someFunction1, someFunction2 } = require('otherModule.js');

import async function from the module

I have a function that looks like this
let fileCache = {};
async function generateFromFile(fullPath) {
if (!fileCache[fullPath]) {
let jsonResource = await fs.readFile(fullPath);
fileCache[fullPath] = JSON.parse(jsonResource);
}
return fileCache[fullPath];
}
When I use it in the same module like this
await generateFromFile('myfile.json');
it works fine.
I created a separate file, put the function there and exported it like this
let fileCache = {};
async function generateFromFile(fullPath) {
if (!fileCache[fullPath]) {
let jsonResource = await fs.readFile(fullPath);
fileCache[fullPath] = JSON.parse(jsonResource);
}
return fileCache[fullPath];
}
module.exports = {
generateFromFile: generateFromFile
}
I imported it like this
const utils = require('../util/utils.js');
and wanted to use like await utils.generateFromFile('myfile.json'); but it fails with the error
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
What is the problem?
How did you import your fs module. To use readFile with await your should
either write fs.promise.readFile
or import fs as
import { promises as fs } from 'fs'
Are you sure that your newly created file is in the relative directory ../util/utils.js? Your export looks fine. Maybe try to print out the imported utils object to see what you actually imported.
EDIT: You are also passing relative filenames to your function which is now in a different diretory than before. When accessing fs.readFile(fullPath) it tries to read the file inside the directory "util/". You should call your function with a full filepath like util.generateFromFile(path.join(__dirname, "myfile.json")) using the path node package.
EDIT 2: Like Raeesaa state you are using fs.readFile wrong. It does not return a Promise but expects a callback. To is it with await you have to promisify it like so:
const fs = require("fs");
const { promisify } = require("util");
const readFileAsync = promisify(fs.readFile);
let fileCache = {};
async function generateFromFile(fullPath) {
if (!fileCache[fullPath]) {
let jsonResource = await readFileAsync(fullPath);
fileCache[fullPath] = JSON.parse(jsonResource);
}
return fileCache[fullPath];
}
module.exports = {
generateFromFile: generateFromFile
}
EDIT 3: If you only import JSON files you can do it by using require. Internally, require has also a cache so imports are only executed once. You can import JSON files as objects like so: const obj = require("myfile.json");

Nodejs pass log instance between modules

I’ve logger which I initiate using a constractor in the index.js file. Now I need
To pass the logger instance to other files, and I do it like this
index.js
const books = require(“./books”);
books(app, logger);
logger = initLogger({
level: levels.error,
label: “app”,
version: "0.0.1",
});
app.listen(port, () => logger.info(`listening on port ${port}`));
And inside the books.js file I use it like following, get the logger from the index.js file and use it
inside the books.js file, also pass it to another file with the function isbn.get(books, logger);,
Is it recommended to do it like this? Is there a cleaner way in nodes ?
books.js
const isbn = require(“./isbn”);
module.exports = async function (app, logger) {
…
try {
Let books = await getBooks();
logger.info(“get “books process has started”);
} catch (err) {
logger.error("Failed to fetch books", err);
return;
}
…
// this function is from the file “isbn” and I should pass the logger to it also
try {
let url = await isbn.get(books, logger);
} catch (e) {
res.send(e.message);
}
}
Try creating a module specifically for your logger configuration, then you can import that into your modules instead of using a side-effect of your business module to create a logger.
This will help if you ever need/want to change your logger configuration - instead of following a chain of business methods, you can just update the log configuration.
Example
logger.js
'use strict';
// Any setup you need can be done here.
// e.g. load log libraries, templates etc.
const log = function(level, message) {
return console.log(level + ": " + message);
};
module.exports = log;
business-logic.js
'use strict';
var log = require('./logger');
var stuff = require('./stuff');
const do_stuff = function (thing) {
// do stuff here
log("INFO", "Did stuff");
}
This is a pretty clean way of doing it, however it could be awkward when trying to share more variables or adding more requires. So, you could put all the variables in an object and destructure only the variables you need in books.js:
index.js:
const state = {app, logger, some, other, variables};
require("./books")(state);
require("./another_file")(state);
books.js:
module.exports = async function ({app, logger}) {
};

Configuring Cypress.env() variable to an imported module file

I'm trying to set & config a new env variable in Cypress.io. In the file cypress/plugins/index.js, I have imported another file like so:
const { getBranch } = require('path/to/file/goes/here/getBranch');
Then, I'm trying to set the new env variable like so:
// cypress/plugins/index.js
module.exports = (on, config) => {
terminalReport.installPlugin(on);
const configuration = config;
configuration.env.injectMainBranchId = getBranch('develop');
// more code below...
However, this is not working. However, if I hardcode the value it does work:
configuration.env.injectMainBranchId = 'develop';
You see the result in the screenshot below:
This is the dummy content of getBranch module:
const getBranch = branch => {
return branch;
};
module.export = { getBranch };
What am I doing wrong?
Typo in getBranch:
const getBranch = branch => {
return branch;
};
module.export = { getBranch };
export should be changed to exports

How to call module with object Parameter in main file Index.js

I need to call module from main index.js File
Here is my module
const request = require('./rq.js');
const callback = require('./callback.js')
const url = `https://localhost.3000/${id}`;
request(url, callback)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
module.exports = page; //Tell me how to export all code from module
So here is my index.js file
const Methods = {
page: require('./page.js'),
}
module.exports = //What i need to code here?
File from what i give a call a module :
const main = require('./index.js');
main.page({id: 'id'})
.then(console.log);
So what I should change to call page.js file like that ?
Make the following changes to page.js since in your main file you expect a promise to be returned.
const request = require('./rq.js');
const callback = require('./callback.js')
function page({id}) {
const url = `https://localhost.3000/${id}`;
return request(url, callback)
}
module.exports = {page: page} //Tell me how to export all code from module
Make the following changes to Mehods.js
const Methods = {
page: require('./page.js').page,
}
module.exports = Methods;
Check if this works.

Categories

Resources