How to edit File in perfoce with node js? - javascript

If i have the code below how can i edit the specific file and make the right corrections?
var p4 = require('C:/Program Files/nodejs/node_modules/p4');
var File = process.argv[2];
p4.edit(File, function(err, data) {
if (err) {
console.error(err.message);
}
console.log(data);
});

Your code looks correct to open the file for edit. If that returns any errors when you run it, you should post those here, but I'll assume that it returns a success message ("(file) opened for edit").
Opening the file for edit means that it is made writable on the local filesystem (i.e. the one where this code is running -- the file is the one you passed as an argument to the edit command). To actually modify the file you can use any other function at your disposal.

Related

fs.write json file to capture and save streaming json file

I want json stream stored in text file. When running the node server, the json file isn't appended to the json.txt file. What am I missing? Am new to to node, so be gentle..
Here is a code chunk I expect to capture the json content:
var fs = require('fs');
fs.writeFile("json.txt",{encoding:"utf8"}, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
The issue is you aren't using the correct parameters. When calling fs.writeFile it expects a string for the filename, a buffer or string for the content, an object for the options and a callback function. What it looks like you're doing is sending the options as the second parameter when it expects a buffer or a string. Correction below;
var fs = require('fs');
fs.writeFile("json.txt", JSON.stringify({some: object}), {encoding:"utf8"}, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
You can replace the JSON.stringify part with some plain text if you wanted to, but you specified JSON in your question so I assumed you wanted to store some object in a file
Source (NodeJS documentation)
EDIT:
The links to other questions in the comments may be more relevant if you want to add new lines to the end of the file and not completely overwrite the old one. However I made the assumption that fs.writeFile was the intended function. If that wasn't the intention, those other questions will help a lot more
UPDATE:
It seems the issue was the fact that the body wasn't being parsed, so when the POST request was going through, Node didn't have the request body. To alleviate this, during the express configuration, the following code is needed:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Uses the npm module body-parser. This will convert the JSON body to a JavaScript object, and it is accessible via req.body.

How to download a URL in JavaScript (Nodejs)?

I used this link to make an original link into a download link:
https://milanaryal.com/2015/direct-linking-to-your-files-on-dropbox-google-drive-and-onedrive/
Now how do I actually use that download link to download the file in JavaScript? I want to do something like:
link = 'https://drive.google.com/uc?export=download&id=FILE_ID';
let x = download(link); //now x is the download file
I looked it up and it seems like there are ways of doing this with HTML/jQuery, but I am not using those because I am working on the server side with Nodejs. I am doing this download thing because I want to check if the file is a pdf or text, parse the text, and then search through it using Elasticsearch.
It's easiest to use a module such as Request to do a HTTP get from a node script.
For example:
var request = require('request');
request.get('https://drive.google.com/uc?export=download&id=FILE_ID',
function(err, res, body){
if(err) return console.log(err);
console.log(body);
});
Once the file has downloaded, the callback function is run with the downloaded file in the body variable
If you only want to download the file, open it, search for data and delete it, you can easily edit this code snippet: https://stackoverflow.com/a/11944984/642977

error ENOENT,open with gridFS and node js

I am trying to save a project and its file using GridFS. I want to save project first and use "_id" of project as metadata for file.
Here is my code:
newProject.save(function (err,project) {
if (err) {
console.log('save error', err);
}
console.log("project added");
var id=poject._id;
var filepath = req.files.file.path;
var filename = req.files.file.name;
var writestream = gfs.createWriteStream({ filename: filename, metadata:id });
console.log(filepath);
fs.createReadStream(filepath)
.on('end', function() {
})
.on('error', function(err) {
console.log("error encountered"+err);//ENOENT,open error
})
.pipe(writestream);
});
I am getting following error:-
ENOENT, open '/tmp/45e85388793de'
I know that this error comes when the directory does not exists. As you can see I am writing the file after saving the project since I need to link the file to the project. That's why I have written the code to save the file inside callback function of project.save() but it is not working there. If I put the same code outside the .save block the same code works perfectly for same path. (I have displayed the path both inside and outside and they are same)
Finally I was able to fix this myself:-
File is saved in a temporary location. When you are inside the callback function your file is removed from that location and you are getting "No such file" error. Path and other variables still exists as part of js and that's why you are able to print them in console.
Solution: Above(Outside) callback function move your file to some other permanent location using:
fs.rename(req.files.file.path, "./someKnownPath/filename");
Keep note of that location. In your callback function use the new location as path and try saving the file in gridfs. Once the file is saved you may delete it file from that location(/someKnownPath/filename).

fs.writeFile has no errors, but fails to write file

I am using node.js, trying to save a file, no errors are thrown, yes the image won't save. This is how I am saving the file:
var url = 'captures/' + getFileName() + '.png';
fs.writeFile(url, base64, 'base64', function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
With a helper to make the file names for me:
function getFileName(){
var d = new Date()
return d.getMonth()+'-'+d.getDate()+'-'+d.getYear()+'-'+d.getHours()+'-'+d.getMinutes()+d.getSeconds();
}
Anyone had trouble with this?
the problem is because this call is async and probably is loosing the context right after, I was able to fix it on my end by using fs.writeFileSync which does it synchronously. hope this helps
Add a console.log('captures/' + getFileName()) just to make sure your file name is correct. When I had this problem it turned out that I had a problem with the file path/name and node just wasn't throwing me an error to explain.
For Typescript version,
Just sharing my experience here, In my use case had a JSON file where I used to store some temporary data read it and make some changes and update it and store that updated data to same JSON file will be used for next cycle.
fs.writeFile was not throwing any error at same time it was not updating my JSON file where as JS version worked well, Then I realized that typescript made these changes in my root or src directory. Created another JSON file there.
If you want to write your file asynchronously, try using fs/promises instead of fs.
const { writeFile } = require("fs/promises");
(async () => {
await writeFile('myFile.txt', 'my content', (err) => {});
})();
writeFile from fs is void. It will execute asynchronously but not in the async-await meaning. writeFile from fs/promises returns a Promise so async-await will work as expected.
Learn more here: https://nodejs.org/api/fs.html#callback-example
There might be a permission issue.
go inside the directory that you are saving your files and then
sudo chmod 777 .

how to handle error while extracing the zip file in node.js

i am trying to upload zip file and then i have to extract it in server side and also i have to handle error while extracting that zip file.to extract i am trying like this
var zip = new AdmZip(x);
zip.extractAllTo('target path');
the extractAllTo not contain call back function ,if it is contain that i can handle err easily so let me know how to handle err while extracting zip file.
i am creating one tmp folder and after upload file and then i keep that uploaded file into tmp folder and then i am storing that uploaded file into original folder and i will take that path to store db(mongodb).After stored data i got stored result in callback function within that callback function i have tried to remove that tmp folder but i could not remove it.i have tired to remove without that data stored callback function it is working . what mistake i did.how to resolve it.i have tried like this
db.save({'filepath':'xxxxx'},function(err,data)
{
if(data)
{
fs.rmdir('xxxx/xxxxx',function(err)
{
if(err)
{
console.log('err')
}else
{
console.log('removed');
}
});
}
});
i am always received in console that err.
After looking in the code from adm-zip, the only way is to embed extraction in a try {} catch statement:
var zip = new AdmZip(x);
try {
zip.extractAllTo('target path');
} catch ( e ) {
console.log( 'Caught exception: ', e );
}
It looks like your library is synchronous, which is why it doesn't use callbacks. If you are uploading a zip file to a server, synchronous calls will halt your entire server for all clients and thus you should switch to an asynchronous library to do this work. FYI for the synchronous version, to handle errors, you would use a try/catch structure as the exceptions thrown are in a single execution stack.

Categories