hey so I'm trying to const some JSON
const cidc = require('./cid/cid.json')
const dc = require('./details/cid.json')
const lc = require('./lik/cid.json')
if(!cidc){
return
}else{
fs.unlinkSync('./src/main/setting/cid/cid.json')
} if(!dc) {
return
}else {
fs.unlinkSync('./src/main/setting/details/cid.json')
} if (!lc){
return
}else {
fs.unlinkSync('./src/main/setting/lik/cid.json')
}
so I'm trying to delete the dc file and it error
how can I make if there is no such file named that it will do nothing (aka return nothing)
and if there is a file named that it will const it to a variable
Since require throws an error of Error: Cannot find module ... and you don't catch those errors, your script will fail.
You could define a new require-function where you catch the error and return undefined:
function safeRequire(path) {
try {
return require(path);
} catch(err) {
return undefined;
}
}
Then use this function in your script:
const cidc = safeRequire('./cid/cid.json')
const dc = safeRequire('./details/cid.json')
const lc = safeRequire('./lik/cid.json')
// rest of your code
Also you can simplify your if/else conditions by inverting the condition:
if (cidc) {
fs.unlinkSync('./src/main/setting/cid/cid.json')
}
if (dc) {
fs.unlinkSync('./src/main/setting/details/cid.json')
}
if (lc){
fs.unlinkSync('./src/main/setting/lik/cid.json')
}
Alternatively you don't even need to use require at all, just check if the files exist using e.g. fs.access(...).
You could directly use unlink with try catch without any requires
function unlink(filePath) {
try {
fs.unlinkSync(filePath);
} catch (e) {
//ignore
}
}
unlink('./src/main/setting/cid/cid.json')
unlink('./src/main/setting/details/cid.json')
unlink('./src/main/setting/lik/cid.json')
Related
I can't seem to figure out why I am getting this error
Uncaught TypeError: work.filter is not a function
at computing_experience.js:7
at Array.map (<anonymous>)
at computing_experience.js:5
when running the filter method on an array (imported from a separate file) anyone have any ideas?
import workExpArray from "../Arrays/workExpArray.js";
const workx = document.querySelector(".workexp");
const newArticle = workExpArray.map((work) => {
let arrayItem = work
.filter(function (workexp) {
if (workexp.industry === "Computing") {
return true;
} else if (workexp.industry != "Computing") {
return false;
}
})
.map((workexp) => {
let workExpArticle = document.createElement("article");
workExpArticle.classList.add("workexp__article");
workExpArticle.setAttribute("id", workexp.id);
if (typeof workexp.secondaryRole === "string") {
workExpArticle.innerHTML = `
<SOME HTML HERE>
`;
} else {
workExpArticle.innerHTML = `
<MORE HTML HERE>
`;
}
return workExpArticle;
});
if (workexp.industry === "Computing") {
arrayItem.forEach((workexp) => {
workx.append(workexp);
});
}
});
This is my first question on here and I'm reasonably new to writing code, so you may need more context :) let me know if so!
Thanks for any help!
Ollie
error occurs when you call work.filter it seems to me that the work is not an array due to which there is no function named filter to call, that's why error is thrown. Make sure your imported array is 2 dimensional meaning it's elements are also arrays
Problem is that you are try to call .filter method on an object ! (work) instead of calling it on work I think what you wanted was to call it on workExpArray ....
Solution =>
// Note used workExpArray intead of work !
const newArticle = workExpArray.map((work) => {
let arrayItem = workExpArray.filter(function (workexp) {
if (workexp.industry === "Computing") {
return true;
} else if (workexp.industry != "Computing") {
return false;
}
});
// ..... further code
});
I have a command that overwrites pause to add the input from a dialog to the reports. I want to know if there is a way to know what test is calling the function so that I can customize the message on the inputs.
Cypress.Commands.overwrite('pause', (originalFn, element, options) => {
var tryThis = '';
if (//place calling the function == file1) {
tryThis = 'message1';
} else if (//place calling the function == file2) {
...
} else if (//place calling the function == file3) {
...
}
var datalog = window.prompt(tryThis, "Log your results");
cy.addContext("DATALOG:" + datalog);
return originalFn(element, options)
})
As well as access via the Mocha properties there is also
For the spec file Cypress.spec
Properties for my.spec.js
Cypress.spec.absolute: "C:/.../my.spec.js"
Cypress.spec.name: "my.spec.js"
Cypress.spec.relative: "cypress\integration\my.spec.js"
Cypress.spec.specFilter: "my"
Cypress.spec.specType: "integration"
For the test cy.state('runnable')
For
describe('my-context', () => {
it('my-test', () => {
Properties and methods,
const title = cy.state('runnable').title; // "my-test"
const fullTitle = cy.state('runnable').fullTitle(); // "my-context my-test"
const titlePath = cy.state('runnable').titlePath(); // ["my-context", "my-test"]
You can also add metadata to the test
describe('my-context', () => {
it('my-test', { message: "my-message" }, () => {
and grab it in the command overwrite
const message = cy.state('runnable').cfg.message; // "my-message"
I tried this and it worked for me (my version of cypress is 6.1.0):
cy.log(Cypress.mocha.getRunner().suite.ctx.test.title);
More info: https://github.com/cypress-io/cypress/issues/2972
I found some legacy code where a factory load one file from sub-tree directory.
var name = 'file.js'
try {
return require('folder/foo/' + name)
} catch (e) {
try {
return require('folder/foo/bar/' + name)
} catch (ee) {
return null
}
}
How can I avoid the nested try/catch blocks for each folder level?
I tried this.
const name = 'file.js'
const pathList = ['folder/foo/', 'folder/foo/bar/']
return pathList.map(path => {
const file = `${path}${name}`
try {
return require(file).default
} catch (exception) {
return null
}
})
But this changes the behaviour. If the file is not found on first level it returns null instead of taking the next level. It doesn't help if I change the order at the pathList declaration.
Is there a better way in a React app environment? I cannot use FS from node.js.
I am new to nodejs and java script.
I am trying to read a config.json file in nodejs project using the below code snippet.whenever i run the program it's giving an error 'TypeError: Cannot set property 'getProjectSettings' of undefined'
Can some one help me to find the issue with the code?
var Env = "DEV"
function getConfigValue(configKey, subConfigKey, isblnEnvattr, callback) {
return callback(configKey, subConfigKey, isblnEnvattr);
}
function readConfigJson(configKey, subConfigKey, isblnEnvattr) {
if (Boolean(isblnEnvattr) == true) { //eg MONGODB_DEV
configKey = configKey + "_" + Env;
}
try {
return 'x';
} catch (err) {
return "key Not found";
}
}
module.export.getProjectSettings = function (configKey, subConfigKey, isblnEnvattr) {
return getConfigValue(configKey, subConfigKey, isblnEnvattr, readConfigJson)
}
getProjectSettings("Primary","secondary",false)
You have a typo - it should be module.exports, not module.export.
module.exports.getProjectSettings = function (configKey, subConfigKey, isblnEnvattr) {
return getConfigValue(configKey, subConfigKey, isblnEnvattr, readConfigJson)
}
Also, you can skip module before export, as long as you are not trying to export only one function (like such exports = function () { ... }).
exports.getProjectSettings = function (...) { ... }
Several of my functions require the UniversalXPConnect privilege to be enabled.
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
So, my functions look like this:
function oneOfMyFunctions() {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// ...
}
Actually, I also try to catch the exception when the privilege is denied. Looks as follows:
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// ...
} catch (e) {
// ...
}
I'd rather to make that a separate function and call it from within my functions as follows:
function oneOfMyFunctions() {
if (enablePrivilege()) {
// ...
} else {
// ...
}
}
Given that the enablePrivilege function would be as follows:
function enablePrivilege() {
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
} catch (e) {
return false;
}
return true;
}
But, for security reasons, that is impossible as the privilege is granted only in the scope of the requesting function.
So, the only option is to include that block of code into each of my functions?
UPDATE:
As I am going to also try to catch some other exceptions I've ended up with the following design:
function readFile(path, start, length) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var file = Components.classes['#mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(path);
var istream = Components.classes['#mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, -1, -1, false);
istream.QueryInterface(Components.interfaces.nsISeekableStream);
istream.seek(0, start);
var bstream = Components.classes['#mozilla.org/binaryinputstream;1'].createInstance(Components.interfaces.nsIBinaryInputStream);
bstream.setInputStream(istream);
return bstream.readBytes(length);
}
var filepath = 'C:\\test.txt', start = 440, length = 5;
try {
console.log(readFile(filepath, start, length));
} catch (e) {
if (e.name == 'Error') console.log('The privilege to read the file is not granted.');
else console.log('An error happened trying to read the file.');
}
You could make enablePrivilege a sort of wrapper function that accepts a function as a parameter that it then calls inside itself, like so
function enablePrivilege(funcParam) {
//enable privileges, in try-catch
funcParam();
}
so that when you call it like so
enablePrivilege(oneOfMyFunctions);
the function that needs the privileges should have them since it is called inside the scope of enablePrivilege.