I want to convert .xls file in JSON format I have used xls-to-json module for the same.
when I used xlsx-to-json module it is working fine. but I don't want to read .xlsx file. it is giving me an error with :
TypeError: Cannot set property length of [object Object] which has only a getter.
I am unable to find an error. is there any other module to convert .xls file in JSON.
here is my code :
var node_xj = require("xls-to-json");
app.get('/file',function(req,res){
node_xj({
input: 'file.xls', // input xls
output: "output.json", // output json
sheet: "sheetname", // specific sheetname
}, function(err, result) {
if(err) {
console.error(err);
} else {
console.log(result);
}
});
});
That package supports only the new xlsx format used by MS Excel.
The easiest option would be to save the file as comma-delimited csv file (as the format is available in most softwares) and use a csv to json converter.
There's a nice one here - https://www.npmjs.com/package/csv
You can use path module to get file extension, and if the file extension is match then execute the parsing code
var node_xj = require("xls-to-json");
var path = require('path');
app.get('/file', function(req, res) {
//Give file name with extension e.g, file.xls
if (path.extname('file.xls') === '.xls') {
node_xj({
input: 'file.xls', // input xls
output: "output.json", // output json
sheet: "sheetname", // specific sheetname
}, function(err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
}
});
Update
This is not an issue of this module, but the issue comes from third-party module dependency xlsjs
here is the opened issue you can see the updates
You can use this module, note I am the author.
The xls-to-json-lc's package has been merged into xlsx-to-json-lc's package. Just use the Xlsx for both types of extensions and will work fine.
Related
"New to programming"
I have a CSV file at
http://vhost11.lnu.se:20090/assig2/data1.csv
I am trying to convert it to a local json file. My code below.
I am getting {"X":"153","Y":"21","time":"21438"}} value in my data1.json.
const request=require('request')
const csv=require('csvtojson')
const fs = require('fs')
csv()
.fromStream(request.get('http://vhost11.lnu.se:20090/assig2/data1.csv'))
.on("json",function(jsonObj){ //single json object will be emitted for each csv line
console.log(jsonObj);
fs.writeFile("./data1.json", JSON.stringify(jsonObj), (err) => {
if (err) {
console.error(err);
return;
};
});
});
Where did I go wrong?
The callback function in the on event is called for each line. You'll want to initialize an empty list in the outer most scope and push jsonObj to it from the callback in on. You can then write your list to a file when the input file is done being read by handling the done event.
I am using papaParse
and I want to save result of this package into file and users can download it. what is the best way to do this? also I am use this node.js code for do it
var csv = Papa.unparse(Users.find().fetch());
console.log("csv : " + JSON.stringify(csv)); // get csv format (not in file)
fs.writeFile("meteorProject/public/", csv, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
but give this error
{ [Error: EISDIR: illegal operation on a directory, open 'meteorProject/public/']
I20160907-13:00:26.970(4.5)? errno: -21,
I20160907-13:00:26.970(4.5)? code: 'EISDIR',
I20160907-13:00:26.970(4.5)? syscall: 'open',
I20160907-13:00:26.970(4.5)? path: 'meteorProject/public/' }
and how can resolve it ??
thanks :-)
This is the issue related to directory please check the directory path you are given here. i.e. - "meteorProject/public/".
So what you need to change is just the directory name you are using .
As i tried with my directory and its running well.
Or i suggest you to try with the fileName.csv as well while saving the file
like:- meteorProject/public/test.csv
or just completely change the path of directory like as i tried with my ubuntu machine and its running well.
var userArray = Users.find().fetch();
var data = Papa.unparse(userArray);
console.log("data is....");
console.log(data);
fs.writeFile('/home/parveen/test/test.csv',data,function(err,res){
if(err){
console.log("err while saving");
console.log(err)
}
else{
console.log("File saved");
console.log(res);
}
});
The above code save the file in the test folder via test.csv name.
Please check and let me know if you again facing any issue.
If you want to know about your error in depth then please see the link:-
https://github.com/bekk/grunt-retire/issues/2
Hope this would help!
Thanks
finally I used this package: Meteor-Files
for solving this problem!
this is sample code:
export(){
var csv = Papa.unparse(Users.find({},{fields:{_id:0}}).fetch());
Exports.write(csv,{
fileName: 'backup'+ new Date().getTime() +'.csv',
type: 'text/csv'
}, function (error, fileRef) {
if (error) {
throw error;
} else {
console.log(fileRef.name + ' is successfully saved to FS. _id: ' + fileRef._id);
}
});
},
Exports is collection .This is the function that helped me.
I want to read a local Json file from a html page. But I am not able to read the local Json file in HTML page that work for chrome and IE.
Is there is any way to do it without using any web server.
Let's say you have,
index.html & sample.json in the same folder,
you can do this,
$http.get('sample.json').then(function(response) {
console.log(response);
});
of course you will need to run this from a controller, stand alone or in a directive, etc.
I found this solution on the web, i didn't try it but according to the comments it should work
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}``
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Create a JSON file named sample.json in a translation folder .Then in controllers use the below code to get the values present in JSON file
$http.get('translation/sample.json').success(function(response){
console.log(response);
});
or
$.getJSON('translation/sample.json', function(data){
console.log(data);
});
How to get a local big json data?
I have tried this, but I had no success:
var sa = require("./shared/resources/sa.json");
var array = new observableArrayModule.ObservableArray(sa);
Use the file-system module to read the file and then parse it with JSON.parse():
var fs = require('file-system');
var documents = fs.knownFolders.currentApp();
var jsonFile = documents.getFile('shared/resources/sa.json');
var array;
var jsonData;
jsonFile.readText()
.then(function (content) {
try {
jsonData = JSON.parse(content);
array = new observableArrayModule.ObservableArray(jsonData);
} catch (err) {
throw new Error('Could not parse JSON file');
}
}, function (error) {
throw new Error('Could not read JSON file');
});
Here's a real life example of how I'm doing it in a NativeScript app to read a 75kb/250 000 characters big JSON file.
TypeScript:
import {knownFolders} from "tns-core-modules/file-system";
export class Something {
loadFile() {
let appFolder = knownFolders.currentApp();
let cfgFile = appFolder.getFile("config/config.json");
console.log(cfgFile.readTextSync());
}
}
As of TypeScript version 2.9.x and above (in NativeScript 5.x.x is using versions 3.1.1 and above) we can now use resovleJsonModule option for tsconfig.json. With this option, the JSON files can now be imported just as modules and the code is simpler to use, read and maintain.
For example, we can do:
import config from "./config.json";
console.log(config.count); // 42
console.log(config.env); // "debug"
All we need to do is to use TypeScript 2.9.x and above and enable the propety in tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
A sample project demonstrating the above can be found here
I just wanted to add one more thing, which might be even easier. You can simply write the content of your JSON file in a data.js file, or whatever name you would like to use, and export it as an array. Then you can just require the data.js module.
I'm trying to save JSON data in my Ionic app to the local device storage. I would like to use the ngCordova File plugin. I can't seem to find any tutorials or example apps that use the exact methods they have in the docs.
Has anyone used this plugin before to save JSON data? How did you do it?
ngCordova takes away a lot of the ugliness of writing files using the file writer API.
This example has been adapted from the docs, and uses writeFile(path, file, data, replace) where the path is defined by cordova.file.DIRECTORY_TYPE, file is a string name for the file, data is the string representation of the data (so we will use JSON.stringify()). Replace is a boolean that will simply erase the existing contents of the file.
//Write using cordova.file.dataDirectory, see File System Layout section for more info
var json = {"test": "hello world"}
$cordovaFile.writeFile(cordova.file.dataDirectory, "hello.json", JSON.stringify(json), true)
.then(function (success) {
// success
}, function (error) {
// error
console.log(error); //error mappings are listed in the documentation
});
For a controller, supposing we are using controllerAs syntax it could look something like this:
angular.controller("...",['$cordovaFile' function ($cordovaFile) {
var vm = this;
vm.writeFile = function (fileName) {
ionic.Platform.ready(function(){
// will execute when device is ready, or immediately if the device is already ready.
var json = {"test": "hello world"}
$cordovaFile.writeFile(cordova.file.dataDirectory, "hello.json", JSON.stringify(json), true)
.then(function (success) {
// success
}, function (error) {
// error
console.log(error); //error mappings are listed in the documentation
});
});
};
});