Node javascript require js file? - javascript

I just want to load the content of a js file into my variable ! but it's returning me an object ? how can i achieve that ?
server.js
const file = require("./server/file.js");
ctx.body = `${file}`; // Should return "(function () { console.log("ok");})";
//file.js
(function () {
console.log("ok");
});

Use file reader for this, check out this documentation NodeJs website
var fs = require('fs');
fs.readFile('./server/file.js', 'utf8', function(err, data) {
if (err) throw err;
const fileContent = data;
console.log(fileContent);
});

Any CommonJS module will export the value of module.exports which defaults to being an empty object (i.e. what you are seeing).
Your module doesn't explicitly export anything.
It has a function expression that you do nothing with (you don't call it, you don't assign it anywhere, you don't pass it anywhere: it is completely pointless).
If you want to export the function then you need to do so explicitly.
function myFunction() {
console.log("ok");
}
module.exports = myFunction;

Related

Error in const bitmap = fs.readFileSync(file);

function readImageFile(file) {
const bitmap = fs.readFileSync(file);
const buf = new Buffer.from(bitmap);
return buf;
}
dir.files(__dirname, function(err, files) {
if (err) throw err;
console.log(files);
//we have an array of files now, so now we'll iterate that array
files.forEach(function(filepath) {
photo = readImageFile(filepath);
var query = 'UPDATE cloth SET access = "?" WHERE Image = "?"'
if (filepath.substring(35,filepath.length -4)!="x.js"){
values = [
photo,
filepath.substring(35,filepath.length -4)
];
pool.query(query, values, function(err, res) {
if (err) throw err;
console.log("BLOB data inserted!");
const bitmap = fs.readFileSync(file);
TypeError: Cannot read properties of undefined (reading 'readFileSync')
I need to duplicate this function, how do I do it? I have several tables to load the BLOB into
I tried changing the ts values, but all in vain. I'm zero in JavaScript and I need to submit a paper. Please help me.
The error you are getting is because the fs module, which contains the readFileSync function, is not being imported or defined in your code.
To fix this, you need to import the fs module at the top of your code by adding this line:
const fs = require('fs');
To duplicate the function, you can simply copy and paste the entire readImageFile function and give it a different name. However, keep in mind that if you are going to use the new function in a different file, you will need to import the fs module in that file as well.

JavaScript export array from one file to another to be used. Node.js

Perhaps you can help.
I have a file the is listing the DIR then pushing it to an array. I'm then trying to export it and use it in another file. But its not working....
File 1.js
const fs = require('fs');
let filename = [];
module.exports = function(){
try {
let subfolder = './DIR/';
fs.readdir(subfolder, async (err, files) => {
for (const file of files) {
filename.push(file);
}
});
}
catch (e) {}
};
File 2.js
let instance = require('../../File 2');
console.log(instance);
However when I run this I get an empty array back. however I can console.log within the file 1.js for the array and it shows correctly. Not sure what I'm doing wrong.
You're exporting a function, not an array.
The array will be filled asynchronously. When you console.log in File 2.js, the array will still be empty.
Result was changing File 1.js to be the following:
const fs = require('fs');
module.exports =
{
getRArray: function ()
{
let filename = [];
try
{
let subfolder = './DIR/';
let files = fs.readdirSync(subfolder);
for (let file of files)
{
filename.push(file);
}
}
catch (e)
{
}
return filename;
}
};
with File 2.js
let instance = require('../../DIR');
console.log(instance.getRArray());

Writing to file in NodeJS calling from another JS file

I am having a weird issue writing to a file in NodeJS.
I have this code in my FileHandler.js:
module.exports.writeFile = function (arr) {
var fs = require('fs');
console.log(arr);
var file = fs.createWriteStream(__dirname+'\\test.txt',{encoding: 'utf8'});
file.on('error', function (err) {
console.log(err); });
file.on("finish", function() {
console.log("finished");
});
arr.forEach(function (item) {
file.write(item+"\n");
});
file.end();
}
If I append
exports.writeFile(["1","2","3"])
To the end of this file and then run node FileHandler.js
The file is created correctly.
However, if I call the writeFile function from another .js file as:
var R = require("r-script");
const dataHandler = require("./DataHandler");
const fileHandler = require("./FileHandler");
var out = R(__dirname + "\\apriori.R");
exports.getRules = function () {
dataHandler.getListOfPageVisitsBySession(1000781912582,1530781912582,function (result){
//ignored result variable
fileHandler.writeFile(["1","2","3"]);
})
}
and passing the exact same array to the function it doesn't write anything (but the file is created), neither fires err or finish event.
If it matters, the DataHandler method contains a request module and a GET to another API.
Any clue of the problem?
Thanks in advance

Using Jquery in Node Js

I am trying to use JQuery in my Node Js Code but it is not working.
Please see my below Node JS code.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function (request, response) {
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(html);
response.end();
}).listen(8080);
});
require("jsdom").env("", function (err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
$('#div1').append('<div>dd</div>');
});
My Index file is coming properly. There is a Div which has div1 Id in my Index.html but I couldn't append new div into my index.html.
What is the problem? Is there any problem in my code?
In addition, if I define var $ in top of the code and move the $('#div1').append('<div>dd</div>'); code out of the brackets such as
});
$('#div1').append('<div>dd</div>');
var db = require("./db_select");
Node JS throwing an error such as: TypeError: $ is not a function
How can I define a global $ ?
I've changed my code as below because I'm anticipating that it can be a sync problem.
var runHtml = function () {
this.load = function () {
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
console.log('Node Js is working');
http.createServer(function (request, response) {
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(html);
response.end();
}).listen(8080);
});
};
this.createjson = function () {
require("jsdom").env("", function (err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
$('#div1').append('<div>dd</div>');
});
};
if (this instanceof runHtml) {
return this.runHtml;
} else {
return new runHtml();
}
};
var runit = new runHtml();
runit.load().createjson();
However, when I run this code, I'm getting an error from the terminal such as: TypeError: Cannot read property 'createjson' of undefined
Why am I getting this error?
As you can see I have a createjson function and I'm trying to call it after load function as using javascript chaning!
The terminal actually gave it away. When you get the error TypeError: Cannot read property 'createjson' of undefined that tells you where to look. In your code, there is a thing, which has a property of creaetejson, that, at runtime, is undefined.
In your last code snippet, at the end, you have a line that goes runit.load().createjson();. This is a line that has a thing (the call to the load method) that has a property called createjson. Looking at the rest of that code snippet, we see that load is a method of runit, which is defined by the line above it var runit = new runHtml();. If we checkout the runHTML function, we find that it has a method called load. In this method, there is no return statement, so it returns undefined by default.
Returning to the line runit.load().createjson();, we can now see how it is evaluated: runit is a functional style class and load is a method on runit, which returns undefined. You called the load method on the runit class, which means that the line (aside from what it does in the load function) is the same as undefined.createjson().
Now, in regards to solving the problem, there are a number of different ways to go.
The simplest way may be to simply return the object from the load method. If you go that route, I suggest you beef up your knowledge of the keyword this. You may also want to look into the keywords async and await.
Happy Coding

Modules with Arguments NodeJS

I have two files, home.js and module.js in the same directory.
What I'm trying to do is, I'm trying to pass the variable named directory as I call the function I exported from module.js.
It gives me this error:
binding.readdir(pathModule._makeLong(path), req);
Type error: path must be a string.
What I'm trying to figure out is, I've passed the directory variable which is process.argv[2] (contains the path) from home.js as I call the function in module.js that requires the same argument (path).
home.js
var fs = require('fs');
var path = require('path');
var module = require('./module.js');
var directory = process.argv[2];
var extensionRequired = process.argv[3];
function printList(err, data) {
if(err) return err;
list.forEach(function (file) {
if(path.extname(file) === '.' + extensionRequired) {
console.log(file);
}
});
}
module(directory, extensionRequired, printList);
module.js
var fs = require('fs');
var path = require('path');
module.exports = function (directory, extensionRequired, callBack) {
fs.readdir(directory, function(err, list) {
if(err) return err;
callBack(err, list)
});
}
I think you made a mistake, and forgot to rename the list variable:
function printList(err, data) {
if(err) return err;
// Here list => data
data.forEach(function (file) {
if(path.extname(file) === '.' + extensionRequired) {
console.log(file);
}
});
}
In your callback-method, named printList, you set the second argument as data. If you want to access the second argument's value again, you have to use data in your code or reassign it to another variable.
Your method may then look like this:
function printList(err, data) {
if (err) return err;
data.forEach(function (file) {
if(path.extname(file) === '.' + extensionRequired) {
console.log(file);
}
});
}
Additionally, I see two more problems with your code:
In module.js, you're requiring the parameter extensionRequired. If you look closely, you'll find, that it isn't even used in this method. This isn't really an error, but would in my opinion be seen as inelegant. Rather pass it trough to the printList as an additional argument (more the node-typical way IMHO) or use it as a global-scope variable as you are currently doing anyway.
In your module.exports-anonymous function from module.js, you are using if (err) return err;. I'd highly recommend you to not do such a thing. Because this is an asynchronous method, you can't really return something, as the return-statement might actually be executed after you called this method. Instead, pass your error as the first argument of the callback. If there is no error, pass null instead, so you can easily figure out if something unexpected happened. Always check that!
Your module.js could then look something like this:
var fs = require('fs');
var path = require('path');
module.exports = function (directory, callback) {
fs.readdir(directory, function(err, list) {
if (err)
// Error happened, pass it to the callback
callback(err);
else
// Everything ran smooth, send null as the error (no error)
// and the list as the second argument.
callback(null, list)
});
}
Your home.js should then be changed accordingly:
var fs = require('fs');
var path = require('path');
var module = require('./module.js');
var directory = process.argv[2];
var extensionRequired = process.argv[3];
function printList(err, data) {
if (err) {
console.error("An error occurred:", err);
// Exit with an error-code of one to
// tell failure to the calling process and
// prevent printing the probably 'undefined' data-variable
process.exit(1);
}
data.forEach(function (file) {
if(path.extname(file) === '.' + extensionRequired) {
console.log(file);
}
});
}
// extensionRequired removed, as it is not needed
module(directory, printList);

Categories

Resources