edit JavaScript files using node js - javascript

How can I find and edit an attribute value in a JavaScript file using nodeJS.
for example: If i have a file called app.js containing following code.
let title = "hello world";
document.getElementById("arr").innerHTML = title;
how can I change the value of title let title = "hello world"; or any other attribute using nodeJS.

Instead of trying to parse/edit JS files why not use something like JSON which is easy to serialize?
Your gulp task can write whatever values are needed to a file:
const fs = require('fs')
fs.writeFileSync('./blah.json', JSON.stringify({ title: "whatever" }))
Then your code references the JSON file
const title = require('./blah.json').title
document.getElementById("arr").innerHTML = title;

I was able to edit a JavaScript file using regex. my code is below:
function updateFile(filename, replacements) {
return new Promise(function(resolve) {
fs.readFile(filename, 'utf-8', function(err, data) {
var regex, replaceStr;
if (err) {
throw (err);
} else {
regex = new RegExp("(\\" + 'let' + "\\s* ]*" + replacements[0].rule + "\\s*=\\s*)([^\\n;}]+)([\\s*;}])");
replaceStr = "$1" + replacements[0].replacer + "$3";
data = data.replace(regex, replaceStr);
}
fs.writeFile(filename, data, 'utf-8', function(err) {
if (err) {
throw (err);
} else {
resolve();
}
});
});
})
}
usage:
var file = src/app.js
var myNewValue = "Hello";
updateFile(file, [{
rule: 'newApp',
replacer: myNewValue
}], function (err) {
sails.log.info((err));
});
this will edit,
let newApp = lol; to let newApp = Hello;

Related

Save js variable data in txt

I have the following code and I need to save allProducts in a .txt file with json format. How can I achieve that?
var fruit = [{"name: x","id: y",..}, {...},...]
var driedFruitsNut = [{"name: x","id: y",..}, {...},...]
fruit.forEach((item) =>{
item.category = "Fruits & Vegetables";
item.subtCategory = "Fruit";
});
driedFruitsNut.forEach((item) => {
item.category = "Fruits & Vegetables";
item.subtCategory = "Dried Fruits & Nuts";
});
var allProducts = fruit.concat(driedFruitsNut);
I tried something like this; but I have no idea if this is even a correct code:
var fs = require('fs');
fs.writeFile("test.txt", allProducts, function(err) {
if (err) {
console.log(err);
}
});
but when I run node fetchFruitVeg.js in my terminal. I get a text file looking like this:
You can try something like this:
var fs = require('fs');
fs.writeFile("test.txt", JSON.stringify(allProducts), function(err) {
if (err) {
console.log(err);
}
});
since allProducts is a javascript object, first you need to convert it into normal string data to write it in a .txt file or .json file

Write CSV file column title in javascript

This is my code. I am trying to output my data as CSV and I am being successful but I can't add the title of the columns. Although I saved the CSV file but the column titles are missing. Can anyone help in this?
var d= new Date();
var t=d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
var data = dataAWS
var result = data.map(function(val) {
return t+'","'+val.payload.test_data;
}).join('"\n"');
var csvData = '"'+ result +'"';
var fs = require('fs');
fs.writeFile("tempN.csv", csvData, 'utf8', function (err) {
if (err) {
console.log("An error occured while saving CSV.");
return console.log(err);
}
console.log("CSV file has been saved.");
});
Without knowing more I would suggest something like:
data.unshift(column_headers);
var result = data.map(function(val) {
return t+'","'+val.payload.test_data;
}).join("\n")
etc, etc

Attaching base64 encoded file nodejs

I am trying to send a soap request with an attachment. Everything works fine except that the attachment i send is always of zero bytes. The soap server accepts a Base64 encoded file and i had achieved to do it in Java using the code
OutputStream outputStream = new ByteArrayOutputStream()
outputStream.writeTo(fileOutputStream);
Base64.encode(outputStream.toByteArray())//argument passed to the function which sends this to the SOAP API
I want to replicate the same with node but i am unable to do so. Below is the function i am using to achieve this. I am reading some files from the client and trying to send it to the SOAP API. I have marked the place in the code responsible to read and append the data the rest is just for reference.
function createSoapEntryWithAtt(req,response){
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
let filesArr = []
for(objkeys in files){
filesArr.push(files[objkeys])
}
return Promise.all(filesArr.map(item => {
return new Promise((res,rej) => {
var oldpath = item.path;
var newpath = 'C:/user/' + item.name;
**var data = fs.readFileSync(oldpath).toString('base64');
let result = []
for (var i = 0; i < data.length; i += 2)// trying to create a 64bit byte array
result.push('0x' + data[i] + '' + data[i + 1])**
console.log(result)
if(data)
res({ [`${item.name}`]: result })
rej("Error occured")
})
})).then(data => {
let url = config.url
var credentials = {
AuthenticationInfo: {
userName: "user",
password: "passwd"
}
}
let args = {
Notes: "Testing From Node App",
}
let count = 0
for (index in data) {
if (count <= 3) {
**for(keys in data[index]){
//console.log(data[index][keys])
args[`Attachment${++count}_Name`] = keys
args[`Attachment${++count}_Data`] = data[index][keys]//Attaching the file read
}
}**
}
soap.createClient(url, function (err, client) {
client.addSoapHeader(credentials)
client.CreateWorkInfo(args, function (err, res) {
if (err) {
console.log("Error is ----->" + err)
} else {
console.log("Response is -----> " + res)
response.end();
}
})
})
})
});
}
Please ignore this question .... and thanks and sorry if anyone wasted time on this question. The error was a careless mistake from my side in the line args["Attachment${++count}_Name"] = keys
args["Attachment${++count}_Data"] = data[index][keys]. Here as i am incrementing the count in both lines there is a mismatch in the sense that Attachment name will be 1 and then in the second line Attachment data will be 02 and hence the name does not contain any data.

How to get matched string from file using file System and nodejs?

I am passing string from client side and if that string is part of that file content i want to print that line , is it doable using fs and nodejs ?
searvice.js
var fs = require('fs');
var path = require('path');
var async = require('async');
var searchStr;
function readFile(str){
searchStr = str;
// var url = './logs/St/server1.log';
fs.readFile('./logs/St/server1.log', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log('Server Data',data);
inspectFile(data);
});
}
function inspectFile(data) {
if (data.indexOf(searchStr) != -1) {
// do something
console.log('print the matching data');
}
}
exports.readFile = readFile;
You have first to split data by new lines. Try this:
function inspectFile(data) {
var lines = data.split('\n'); // get the lines
lines.forEach(function(line) { // for each line in lines
if(line.indexOf(searchStr) != -1) { // if the line contain the searchStr
console.log(line); // then log it
}
});
}
Note: instead of making searchStr global, you could just pass it as parametter to inspectFile.

Add object to json file - Node.js

I'm trying to add an object to a very large JSON file in Node.js (but only if the id doesn't match an existing object). What I have so far:
example JSON file:
[
{
id:123,
text: "some text"
},
{
id:223,
text: "some other text"
}
]
app.js
var fs = require('fs');
var jf = require('jsonfile')
var util = require('util')
var file = 'example.json'
// Example new object
var newThing = {
id: 324,
text: 'more text'
}
// Read the file
jf.readFile(file, function(err, obj) {
// Loop through all the objects in the array
for (i=0;i < obj.length; i++) {
// Check each id against the newThing
if (obj[i].id !== newThing.id) {
found = false;
console.log('thing ' + obj[i].id + ' is different. keep going.');
}else if (obj[i].id == newThing.id){
found = true;
console.log('found it. stopping.');
break;
}
}
// if we can't find it, append it to the file
if(!found){
console.log('could not find it so adding it...');
fs.appendFile(file, ', ' + JSON.stringify(newTweet) + ']', function (err) {
if (err) throw err;
console.log('done!');
});
}
})
This is so close to what I want. The only problem is the trailing ] character at the end of the JSON file. Is there a way to delete it using the file system API or something? Or is there a much easier way to do exactly what I want?
The proper way to handle this is to parse the JSON file, modify the object, and output it again.
var obj = require('file.json');
obj.newThing = 'thing!';
fs.writeFile('file.json', JSON.stringify(obj), function (err) {
console.log(err);
});
For my project I ended up using this code.
function appendJsonToFile(file, entry, key, callback){
if(!_.isObject(entry)){
return callback('Type object expected for param entry', null);
}
fs.readFile(file, 'utf8', function(err, data){
if(err){
return callback(err, null);
}
var json;
try{
json = JSON.parse(data);
} catch(e){
return callback(e, null);
}
if(!_.isArray(json[key])){
return callback('Key "' + key + '" does not point to an array', null);
}
json[key].push(entry);
fs.writeFile(file, JSON.stringify(json), function (err) {
if(err){
return callback(err, null);
}
callback(null, file);
});
});
}

Categories

Resources