Read java file using nodejs - javascript

I have some .java files inside a directory, I want to read those files and get some values inside each of them. I'm not sure on how to proceed. how can I do this using fs module and some other npm modules in node js.
Below is my current code
const path = require('path');
var fs = require('fs');
module.exports={
readTS: function () {
var CWD = path.join(__dirname, '../');
var folder = path.basename(CWD).toLowerCase();
var TSJavaPath = path.join(__dirname, '../src/main/java/com/'+folder+'/');
var files = fs.readdirSync(TSJavaPath).filter(fn => fn.startsWith('TS'));
console.log(files);
for(i=0;i<files;i++){
//Read and get data
}
}
};

You could compile your .java files and read them using leonardosnt/java-class-tools.
You have HelloWorld.java -
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Then compile -
javac HelloWorld.java
Then write a quick index.js -
const { JavaClassFileReader } = require('java-class-tools');
const reader = new JavaClassFileReader();
const classFile = reader.read('./HelloWorld.class');
classFile.methods.forEach(md => {
/**
* Method name in constant-pool.
*
* Points to a CONSTANT_Utf8_info structure: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.7
*/
const nameInConstantPool = classFile.constant_pool[md.name_index];
// To string (hacky)
const name = String.fromCharCode.apply(null, nameInConstantPool.bytes);
console.log(name);
});
Which outputs the following -
node index.js
<init>
main

Related

How to compress Folder in nodeJS Mac without .DS_STORE

Using the folder-zip-sync npm library and other zipping libraries, The .zip file gets saved with an extra .DS_STORE file. How to zip without this file? Is there a setting I can turn off? How to go about this?
var zipFolder = require("folder-zip-sync");
zipFolder(inputPath, pathToZip);
you don't need any library to compress
for this action use node js build in zlib module
const { createReadStream, createWriteStream } = require('fs');
const { createGzip } = require('zlib');
const inputFile = "./input.txt";
const outputFile = "./input.txt.gz";
const srcStream = createReadStream(inputFile)
const gzipStream = createGzip()
const destStream = createWriteStream(outputFile)
srcStream.pipe(gzipStream).pipe(destStream)

Not able to read files content inside NodeJS

I have some markdown files inside /markdown folder. I am trying to read content of these files. I can see the file names inside the array. But when I try to read it, it doesn't return any data or error. What needs to be done here?
app.get("/", async(req, res) => {
const mdPath = "...path"
const data = await fs.readdirSync(mdPath);
console.log(data) // Return Array of files
for (let i = 0; i <= data.length; i++) {
const fileContent = fs.readFileSync(i, "utf-8");
return fileContent;
}
})
You should use something like path() to better handle the filesystem side.
This could work your way:
const fs = require('fs') // load nodejs fs lib
const path = require('path') // load nodejs path lib
const mdPath = 'md' // name of the local dir
const data = fs.readdirSync(path.join(__dirname, mdPath)) //join the paths and let fs read the dir
console.log('file names', data) // Return Array of files
for (let i = 0; i < data.length; i++) {
console.log('file name:', data[i]) // we get each file name
const fileContent = fs.readFileSync(path.join(__dirname, mdPath, data[i]), 'utf-8') // join dir name, md folder path and filename and read its content
console.log('content:\n' + fileContent) // log its content
}
I created a folder ./md, containing the files one.md, two.md, three.md. The code above logs their content just fine.
>> node .\foo.js
file names [ 'one.md', 'three.md', 'two.md' ]
file name: one.md
content:
# one
file name: three.md
content:
# three
file name: two.md
content:
# two
Note that there is no error handling for anything that could go wrong with reading files.

Read all files in a directory and parse them to JSON

I have a directory full of txt files containing json content. I would like to read the whole directory and rename the files according to the json tag value label.
I know how to read a single file using the below code but how do you read a whole directory?
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
These code gives you list of your files in folder:
var fs = require('fs');
var files = fs.readdirSync('/assets/photos/');
Then you can iterate these list and do your code.
Using the node filesystem (fs) module you can do what you want assuming it's all locally accessible and you have permissions. Here's a way it could work:
const fs = require("fs");
const dir = "/path/to/the/directory";
// get the directory contents
const files = fs.readdirSync(dir);
for (const file of files) {
// for each make sure it's a file (not a subdirectory)
const stat = fs.statSync(file);
if (stat.isFile()) {
// read in the file and parse it as JSON
const rawdata = fs.readFileSync(file);
try {
const json = JSON.parse(rawdata);
if (json.label) {
// build the new filename using 'label'
const newfile = `${dir}/${label}.json`;
fs.renameSync(file, newfile)
}
}
catch (err) {
console.log(`Error working with ${file}. Err: ${err}`);
}
}
}
That's the idea. Additional error checking can be done for safety like making sure the new filename doesn't already exist.

updating json value from a grunt task

I am trying to update a json value from a grunt task i have.
This bit of code works
var number = 123456;
var setRandomNumber = function() {
var fs = require('fs');
var fs = require('fs-extra');
var filename = 'my.json';
var config = JSON.parse(fs.readFileSync(filename), 'utf8');
console.log(config.randomNumber);
};
setRandomNumber();
What I want to do is update config.randomNumber to be the value of number.
Can anyone point me in the right direction?
Ta
here is an example of updating the version of the package.json file using a grunt task. (from 0.0.0 to 1.0.0 to 2.0.0);
module.exports = function(grunt) {
grunt.registerTask('version', function(key, value) {
var projectFile = "package.json";
if (!grunt.file.exists(projectFile)) {
grunt.log.error("file " + projectFile + " not found");
return true; //return false to abort the execution
}
var project = grunt.file.readJSON(projectFile), //get file as json object
currentVersion = project["version"].split('.');
currentVersion[lastIndex] = Number(currentVersion[0]) + 1
currentVersion = currentVersion.join('.');
project["version"] = currentVersion;
grunt.file.write(projectFile, JSON.stringify(project, null, 2));
});
}
now you can call the task version to increment the file by writing
grunt version
or you can add it to your production process, for example:
module.exports = function(grunt) {
grunt.registerTask('buildProd', [
'version'
]);
};

NodeJS - Require and Modules

Does require and module.exports in NodeJS could be used to obtain all functions in all JavaScript files residing in a directory rather than in a single JavaScript file? If so HOW? Could anyone please explain it with an example ?
If require is given the directory path, it'll look for an index.js file in that directory. So putting your module specific js files in a directory, creating an index.js file & finally require that directory in your working js file should do. Hope example below helps....
Example:
file: modules/moduleA.js
function A (msg) {
this.message = msg;
}
module.exports = A;
file: modules/moduleB.js
function B (num) {
this.number = num;
}
module.exports = B;
file: modules/index.js
module.exports.A = require("./moduleA.js");
module.exports.B = require("./moduleB.js");
file: test.js
var modules = require("./modules");
var myMsg = new modules.A("hello");
var myNum = new modules.B("000");
console.log(myMsg.message);
console.log(myNum.number);
By using require
you required the module in that file and you can use the all function of that prototype (single file ) not a complete directory.
e.g
function admin(admin_id)
{
//console.log(parent_id);
this.admin_id = admin_id;
}
//default constructor
function admin()
{
admin_id = null;
self =this;
}
//destructor
~function admin(){
this.admin_id = null;
console.log('admin obj destroyed!');
}
//exporting this class to access anywhere through data encapstulation
module.exports = admin;
//class methods
admin.prototype = {
help:function(params){
console.log('hi');
}
},
you can require this module and can use the function help
and by this method u can require all file (modules) in single file
Wiki: "Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications.
Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript.
The runtime environment interprets JavaScript using Google's V8 JavaScript engine."
Nodejs example:
You have Afile.js
var Afile = function()
{
};
Afile.prototype.functionA = function()
{
return 'this is Afile';
}
module.exports = Afile;
And Bfile.js
var Bfile = function()
{
};
Bfile.prototype.functionB = function()
{
return 'this is Bfile';
}
module.exports = Bfile;
The Test.js file require Afile.js and Bfile.js
var Afile = require(__dirname + '/Afile.js');
var Bfile = require(__dirname + '/Bfile.js');
var Test = function()
{
};
Test.prototype.start = function()
{
var Afile = new Afile();
var Bfile = new Bfile();
Afile.functionA();
Bfile.functionB();
}
var test = Test;
test.start();

Categories

Resources