Trying to read and print local file to console - javascript

I'm new to JS and I'm trying to just print the "loadavg" file to the console when I run my program. I don't want to bother doing it through the browser just yet.
This is what I've come up with
function readTextFile() {
var contents = new File();
contents.readTextFile("file:///proc/loadavg");
console.log(contents);
}
I get no errors but the code still will not work

With Node JS.
Create a folder and enter it:
mkdir filereader
cd filereader
Init Node JS:
npm init
Edit index.js as new file in the directory:
var fs = require('fs');
let filename = '/proc/loadavg';
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log(data)
});
Save, exit the file, and run the script:
node index.js
Image here in the link:
running the script on Ubuntu Terminal

If you dont want to use nodeJS the only way to read text file using javascript is to use file Input
HTML:
<input type="file" id="file_input">
JS:
const fileInput = document.getElementById("file_input")
fileInput.addEventListener("input", (event) => {
const file = e.target.files[0]
if(file){
const reader = new FileReader()
reader.readAsText(file)
reader.onload = () => console.log(reader.result)
}
})

You can use nodejs streams to achieve this.
const fs = require('fs'),
var reader = fs.createReadStream('./proc/loadavg');
stream.on('data', function(chunk) {
process.stdout.write(chunk);
});

Related

React: Read Zip file using JSZip from the project directory

I am trying to read a zip file which has images from the project directory in React.
When I open the Zip file from <input type="file" />, it works by taking the event.target.files[0] .
But when I put that same file in react project and then try to open it by giving a path , it doesnt work.
Example : "./test.zip"
My current code:
let jsZip = new JSZip();
jsZip.loadAsync("./test.zip").then(function (zip) {
let imagess = [];
Object.keys(zip.files).forEach(function (filename) {
zip.files[filename].async("base64").then(function (fileData) {
const image = document.createElement("img");
image.src = "data:image/*;base64," + fileData;
document.querySelector(".unziped-container").appendChild(image);
});
});
});
I have been stuck on this for hours and the documentation is not helping either.
Any help is appreciated.
Anyone coming across this can use JSZip-utils and write the following code
JSZipUtils.getBinaryContent("../path/file.zip", function (err, data) {
if (err) {
throw err;
}
const jsZip = new JSZip();
jsZip.loadAsync(data).then(function (zip) {
Object.keys(zip.files).forEach(function (filename) {
zip.files[filename].async("base64").then(function (fileData) {
const image = document.createElement("img");
image.src = "data:image/*;base64," + fileData;
const unziped = document.querySelector(".unziped-container");
unziped.appendChild(image);
});
});
});
});
the documentation seems pretty clear: the first argument to loadAsync is the zip file data, but you're passing it a string.
(and what you're tring to do won't work anyway. your React code is running in the browser and has no knowledge of filesystem paths or filenames.)

Reading extracting data javascript

I am developping a node js project.I have a zip file i want to extract it then i read one of the files inside my extracted zip.
The problem that i has that even i code the function for extraction before the readfile function that i call it in the callback.
I always has no such file or directory error like the readfile is passed before the extraction.Help!!
This is my code
var unzip = require('unzip');
const fs = require('fs');
var stream = fs.createReadStream(zipFilePath).pipe(unzip.Extract({ path: 'files/em' }));
stream.on('finish', function () {
fs.readFileSync('files/em/data.json') ;//read the extracted file but always the extraction passed after this
});
You don't observe the right event. The 'finish' event of createReadStream() is triggered before the unzip process occurs. You should instead listen to the 'close' event of the unzip process to be sure the extraction is done.
const unzip = require('unzip');
const fs = require('fs');
const zipFilePath = 'files/data.zip'
let extract = unzip.Extract({ path: 'files/em' })
let stream = fs.createReadStream(zipFilePath).pipe(extract);
extract.on('close', () => {
let data = fs.readFileSync('files/em/data.json') ;
console.log(data.toString()) // print your unziped json file
})
path should be a directory, 'unzip.Extract({ path: 'files/em' })'

Extract Sketch file using JavaScript

The purpose is to extract the contents of a .sketch file.
I have a file with the name myfile.sketch. On renaming the file extension to myfile.zip and extracting the same in Finder, I'm able view the files within. I tried doing the same on the server using Node.js by renaming the file extension to .zip. I wasn't able to extract the files, rather I got some ZIP files within the files.
var oldPath = __dirname+'/uploads/myfile.sketch',
newPath = __dirname+'/uploads/myfile.zip';
fs.rename(oldPath, newPath, function (err) {
console.log('rename callback ', err);
});
Is it possible to extract a non-ZIP file using frameworks like JSzip?
As a .sketch file is essentially a ZIP file, the extension does not matter. Any tool that is capable of unpacking a ZIP file will work.
You can verify this with the file command:
$ file myfile.sketch
myfile.sketch: Zip archive data, at least v1.0 to extract
As you are working on the server already, there is nothing stopping you from just using the OS's command line tools like unzip.
Like this:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function unzip() {
const filename = 'myfile.sketch'
const { stdout, stderr } = await exec('unzip ' + filename);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
unzip();
Doing it with JSZip is straight-forward as well:
var fs = require('fs');
var JSZip = require('jszip');
new JSZip.external.Promise(function (resolve, reject) {
fs.readFile('myfile.sketch', function(err, data) {
if (err) {
reject(e);
} else {
resolve(data);
}
});
}).then(function (data) {
return JSZip.loadAsync(data);
})

Uncaught ReferenceError: XLSX is not defined on drop file

I want to be able to drag and drop an excel file, but for some reason when declaring my workbook var workbook = XLSX.read(data, {type: rABS ? 'binary':'array'}); it says it's not defined.
I think I'm missing something to connect this index.js to server.js which has the var XLSX = require('xlsx'); in it. I've looked and looked online and haven't found the right fix. I would like to avoid using a module to require() inside of HTML.
What I think is the important code:
server.js:
var express = require("express");
var app = express();
var XLSX = require('xlsx');
var fs = require('fs');
var JSON = require('JSON');
var path = require('path');
index.js:
$(document).ready(function(){
var rABS = true; // true: readAsBinaryString ; false: readAsArrayBuffer
$excelHolder.on('drop', function(e){
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
console.log("got to before reader");
reader.onload = function (e) {
console.log("got to reader.onload");
var data =e.target.result;
var workbook = XLSX.read(data, {type: rABS ? 'binary':'array'});
var sheet_name_list = workbook.SheetNames;
var excelObj = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
var json = JSON.stringify(excelObj);
var callback = "looks like it worked";
console.log("did it upload?");
fs.writeFile('excelfile.json', json, function(err){
(err) ? console.error(err) : console.log(callback.toString());
});
// preview?
};
if(rABS) reader.readAsBinaryString(file); else reader.readAsArrayBuffer(file);
});
}
index.html:
<div class="huge">22</div>
<div>Uploads!</div>
<input name="uploads[]" type="file" accept=".xls,.xlsx,.ods,.csv" style="display: none;" id="excelInput">
Any help is much appreciated.
I can see a few problems here:
fs and path are modules that are built into NodeJs, hence they are not available in the browser.
You'll need some kind of build tool for your JS if you want to use require for client-side code. Browserify and Webpack are good places to start.
If you don't want to get into that (It's complex so I wouldn't blame you!) you can add the XLSX module to the browser with a <script> tag: https://www.npmjs.com/package/xlsx#installation - it seems like it should work.
There are some examples on the XLSX GitHub page, one of which includes drag & drop and may help you get where you want? https://github.com/SheetJS/js-xlsx (And specifically https://github.com/SheetJS/js-xlsx/tree/master/demos/datagrid)
if you forget to add the library cdn or install it, he will generate this error
add this script or any new:
<script type="text/javascript" src="https://unpkg.com/xlsx#0.15.1/dist/xlsx.full.min.js"></script>

Download a PDF automatically once its generated (Node, Express)

I am using following node module html-pdf
to convert html to pdf. I have successfully converted html to pdf but I am having trouble downloading the file once it has been created.
Code to generate PDF:
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
How can I either open the PDF within the browser for the user to see or automatically download the pdf within the browser without the user having to go through another step.
I just made some changes to your code.In this code I create a route. Whenever you made a request with this route it converts HTML file to PDF and creating a pdf file into your directory from where you are executing. And at the sametime it displays the html file in browser with downloading option also. Hope this helps for you. And here is my code.
var express=require('express');
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('C:/Users/nodejs/tasks/file.html', 'utf8');
var options = { format: 'Letter' };
var app=express();
app.get('/file',function(request,response)
{
pdf.create(html, options).toFile('./businesscaw.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
var file= 'C:/Users/nodejs/tasks/businesscaw.pdf';
fs.readFile(file,function(err,data){
response.contentType("application/pdf");
response.send(data);
});
});
});
app.listen(3000,function(){
console.log("Server listening on port http://loalhost:3000");
});
Output:
See the output in browser like : localhost:3000/file

Categories