Relative path on fs.watchfile using Node.js - javascript

I use this method to read data from the file when it changes. I restructured my project and now the data isn't read anymore.
fs.watchFile("???", (curr, prev) => {
console.log("Änderung auf Data.json");
fs.readFile("Data.json", "utf8", (err, data) => {
widgets = JSON.parse(data);
console.log("Daten ausgelesen" );
io.emit("dataUpdate", {widgets});
});
});
You can see my file paths here. The method above is in client.js and I want to refer to Data.json.
I tried:
"../Data.json" and
"/Server/Data.json"
Thanks for your help!
PS.: I know that there are threads explaining relative paths, but I still couldn't fix my problem.

You can use __dirname https://nodejs.org/docs/latest/api/modules.html#modules_dirname
example:
const path = require('path');
const filePath = path.join(__dirname, '..', 'data.json');

Related

Load local dll with node-ffi: No such file

I try to load a local .dll according the examples on stackoverflow and node-ffi documentation.
But I get the error ENOENT: no such file or directory, open '../test/user32.dll.so'. The file is there (no exception).
The extension '.so' is added automatically. Any idea what I'm doing wrong? Is this code plattform dependent? I'm on Debian.
const path = require('path');
const fs = require('fs');
const ffi = require('ffi');
function setCursor() {
const dllFile = path.join('../test', 'user32.dll');
if (!fs.existsSync(dllFile)) {
throw (new Error('dll does not exist'));
}
const user32 = ffi.Library(dllFile, {
"SetCursorPos": [
"bool", ["int32", "int32"]
]
});
console.log(user32.SetCursorPos(0, 0));
}
setCursor();
It looks like path doesn't recognize ../test as being the parent folder. I think path.join(__dirname, '..', 'test', 'user32.dll'); should get you to the right place.

Node JS filesystem module reading directory exclude files

I have some Node JS javascript code that reads folders inside of a directory, however it's currently reading folders and files, and I just need it to read folders and can't figure out what U'm missing:
router.get('/check', (req, res) => {
fs.readdir('./directory', function(err, files) {
if (err) {
res.status(500).send({ error: { status: 500, message: 'error' } })
return
}
console.log('success')
})
})
I was thinking about doing something like files[0].length > X for instance to only show names that contain more than X characters, or filter out file extensions etc, I ideally just need directories since I have a .empty file inside.
You can check reference on documentation. readdir() will return contents of the directory. You need to filter folders or files. Simply you can call and create new array files.filter(fileName => fs.statSync(path + fileName).isFile().
ref
Update
Given sample code will filter files and folders into to seperated variables. You can implement into your project.
const fs = require('fs');
const path = require('path');
const dir = fs.readdirSync(__dirname);
const folders = dir.filter(element => fs.statSync(path.join(__dirname, element)).isDirectory());
const files = dir.filter(element => fs.statSync(path.join(__dirname, element)).isFile);
console.log('folders', folders, 'files', files);

How to apply a function from node package to all the files in a directory?

I've installed mammoth.js module which converts docx to html. I can use it with a single file.
How do I use the same module for all the files in a specific folder? I'm trying to save an output html files while keeping the original name (not the extension, of course). Probably I have to require some other packages...
The code below is for a single file from the desired directory:
var mammoth = require("mammoth");
mammoth.convertToHtml({path: "input/first.docx"}).then(function (resultObject) {
console.log('mammoth result', resultObject.value);
});
The system is win64
Something like this should work
const fs = require('fs')
const path = require('path')
const mammoth = require('mammoth')
fs.readdir('input/', (err, files) => {
files.forEach(file => {
if (path.extname(file) === '.docx') {
// If its a docx file
mammoth
.convertToHtml({ path: `input/${file}` })
.then(function(resultObject) {
// Now get the basename of the filename
const filename = path.basename(file)
// Replace output/ with where you want the file
fs.writeFile(`output/${filename}.html`, resultObject.value, function (err) {
if (err) return console.log(err);
});
})
}
})
})

How do you get a list of files in a directory with javascript in html on server side?

I am trying to get an array of file names from a server side folder in javascript, how do you do this or are you not able to do this at all? I'm looking for something like this:
var file_names = get_files_by_dir(path)
Using node's asynchronous readdir() method (docs)
function getFiles(folder){
const testFolder = folder;
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
}

Node Winston log file forced string conversion

In a Node project, I want to show the contents of a Winston log file in a React interface. Reading the file:
let content;
fs.readFile("path", "utf-8", function read(err, data) {
if (err)
throw err;
content = data;
});
I send them to the interface:
router.get("/", function (req, res) {
res.status(200).send(JSON.stringify(content));
});
And i get the content in a .jsx file:
getLogs().then(res => {
let datafromfile = JSON.parse(res);
// Use the data
return;
}).catch(err => {
return err.response;
});
The issue i am having is that fs converts all the data into a string (since i am putting the utf-8 encoding and do not want to be returned a buffer) and therefore i cannot manipulate the objects in the log file to show them structurally in the interface. Can anyone guide how to approach this problem?
I have not debugged this, but a lot of this depends on whether or not the the Winston file your loading actually has JSON in it.
If it does then JSONStream is your friend and leaning through or through2 is helpful you in node (streams).
following, code/pseudo
router.get("/", function (req, res) {
const logPath = ‘somePath’; // maybe it comes from the req.query.path
const parsePath = null; // or the token of where you want to attemp to start parsing
fs.createReadStream(logPath)
.pipe(JSONStream.parse(parsePath))
.pipe(res);
});
JSONStream
fs.createReadStream and node docs
through2

Categories