Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 347 Vote(s) - 3.6 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing to files in Node.js

#11
You can write in a file by the following code example:


```
var data = [{ 'test': '123', 'test2': 'Lorem Ipsem ' }];
fs.open(datapath + '/data/topplayers.json', 'wx', function (error, fileDescriptor) {
if (!error && fileDescriptor) {
var stringData = JSON.stringify(data);
fs.writeFile(fileDescriptor, stringData, function (error) {
if (!error) {
fs.close(fileDescriptor, function (error) {
if (!error) {
callback(false);
} else {
callback('Error in close file');
}
});
} else {
callback('Error in writing file.');
}
});
}
});
```
Reply

#12
You may write to a file using [fs][1] (file system) module.

Here is an example of how you may do it:

```javascript
const fs = require('fs');

const writeToFile = (fileName, callback) => {
fs.open(fileName, 'wx', (error, fileDescriptor) => {
if (!error && fileDescriptor) {
// Do something with the file here ...
fs.writeFile(fileDescriptor, newData, (error) => {
if (!error) {
fs.close(fileDescriptor, (error) => {
if (!error) {
callback(false);
} else {
callback('Error closing the file');
}
});
} else {
callback('Error writing to new file');
}
});
} else {
callback('Could not create new file, it may already exists');
}
});
};
```

You might also want to get rid of this callback-inside-callback code structure by useing **Promises** and `async`/`await` statements. This will make asynchronous code structure much more flat. For doing that there is a handy [util.promisify(original)][2] function might be utilized. It allows us to switch from callbacks to promises. Take a look at the example with `fs` functions below:

```javascript
// Dependencies.
const util = require('util');
const fs = require('fs');

// Promisify "error-back" functions.
const fsOpen = util.promisify(fs.open);
const fsWrite = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

// Now we may create 'async' function with 'await's.
async function doSomethingWithFile(fileName) {
const fileDescriptor = await fsOpen(fileName, 'wx');

// Do something with the file here...

await fsWrite(fileDescriptor, newData);
await fsClose(fileDescriptor);
}
```


[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#13
There are a lot of details in the [File System API][1]. The most common way is:

<!-- language: lang-js -->

const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});

// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');



[1]:

[To see links please register here]

Reply

#14
**Synchronous Write**

> fs.writeFileSync(file, data[, options])

fs = require('fs');

fs.writeFileSync("foo.txt", "bar");

**Asynchronous Write**

> fs.writeFile(file, data[, options], callback)

fs = require('fs');

fs.writeFile('foo.txt', 'bar', (err) => { if (err) throw err; });

**Where**

file <string> | <Buffer> | <URL> | <integer> filename or file descriptor
data <string> | <Buffer> | <Uint8Array>
options <Object> | <string>
callback <Function>


Worth reading the offical File System (fs) [docs][1].

**Update: async/await**

fs = require('fs');
util = require('util');
writeFile = util.promisify(fs.writeFile);

fn = async () => { await writeFile('foo.txt', 'bar'); }

fn()


[1]:

[To see links please register here]

Reply

#15
**You can write to files with streams.**

Just do it like this:

const fs = require('fs');

const stream = fs.createWriteStream('./test.txt');
stream.write("Example text");
Reply

#16
Here we use w+ for read/write both actions and if the file path is not found then it would be created automatically.

fs.open(path, 'w+', function(err, data) {
if (err) {
console.log("ERROR !! " + err);
} else {
fs.write(data, 'content', 0, 'content length', null, function(err) {
if (err)
console.log("ERROR !! " + err);
fs.close(data, function() {
console.log('written success');
})
});
}
});

Content means what you have to write to the file and its length, 'content.length'.
Reply

#17
Point 1:

If you want to write something into a file.
means: it will remove anything already saved in the file and write the new content. use **fs.promises.writeFile()**

Point 2:

If you want to append something into a file.
means: it will not remove anything already saved in the file but append the new item in the file content.then first read the file, and then add the content into the readable value, then write it to the file. so use **fs.promises.readFile and fs.promises.writeFile()**

----------------------------
example 1: I want to write a JSON object in my JSON file .

const fs = require('fs');
const data = {table:[{id: 1, name: 'my name'}]}
const file_path = './my_data.json'
writeFile(file_path, data)
async function writeFile(filename, writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata, null, 4), 'utf8');
console.log('data is written successfully in the file')
}
catch (err) {
console.log('not able to write data in the file ')
}
}



-------------------------------------------

example2 :
if you want to append data to a JSON file.
you want to add data **{id:1, name:'my name'}** to file **my_data.json** on the same folder root. just call **append_data (file_path , data )** function.

It will append data in the JSON file if the file existed . or it will create the file and add the data to it.

const fs = require('fs');
const data = {id: 2, name: 'your name'}
const file_path = './my_data.json'
append_data(file_path, data)

async function append_data(filename, data) {

if (fs.existsSync(filename)) {
var read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
} else {
read_data.table.push(data) //data must have the table array in it like example 1
var dataWrittenStatus = await writeFile(filename, read_data)
if (dataWrittenStatus == true) {
console.log('data added successfully')
} else {
console.log('data adding failed')
}
}
}
}

async function readFile(filePath) {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return JSON.parse(data)
}
catch (err) {
return false;
}
}

async function writeFile(filename, writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata, null, 4), 'utf8');
return true
}
catch (err) {
return false
}
}
Reply

#18
Currently there are three ways to write a file:

1. [`fs.write(fd, buffer, offset, length, position, callback`)][1]

You need to wait for the callback to ensure that the buffer is written to disk. It's not buffered.

2. [`fs.writeFile(filename, data, [encoding], callback)`][2]

All data must be stored at the same time; you cannot perform sequential writes.

3. [`fs.createWriteStream(path, [options]`)][3]

Creates a [`WriteStream`][4], which is convenient because you don't need to wait for a callback. But again, it's not buffered.

A [`WriteStream`][4], as the name says, is a stream. A stream by definition is “a buffer” containing data which moves in one direction (source ► destination). But a writable stream is not necessarily “buffered”. A stream is “buffered” when you write `n` times, and at time `n+1`, the stream sends the buffer to the kernel (because it's full and needs to be flushed).

**In other words:** “A buffer” is the object. Whether or not it “is buffered” is a property of that object.

If you look at the code, the `WriteStream` inherits from a writable `Stream` object. If you pay attention, you’ll see how they flush the content; they don't have any buffering system.

If you write a string, it’s converted to a buffer, and then sent to the native layer and written to disk. When writing strings, they're not filling up any buffer. So, if you do:

<!-- language-all: lang-js -->

write("a")
write("b")
write("c")

You're doing:

fs.write(new Buffer("a"))
fs.write(new Buffer("b"))
fs.write(new Buffer("c"))

That’s *three* calls to the I/O layer. Although you're using “buffers”, the data is not buffered. A buffered stream would do: `fs.write(new Buffer ("abc"))`, one call to the I/O layer.

As of now, in Node.js v0.12 (stable version announced 02/06/2015) now supports two functions:
[`cork()`](

[To see links please register here]

) and
[`uncork()`](

[To see links please register here]

). It seems that these functions will finally allow you to buffer/flush the write calls.


For example, in Java there are some classes that provide buffered streams (`BufferedOutputStream`, `BufferedWriter`...). If you write three bytes, these bytes will be stored in the buffer (memory) instead of doing an I/O call just for three bytes. When the buffer is full the content is flushed and saved to disk. This improves performance.

I'm not discovering anything, just remembering how a disk access should be done.

[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

[4]:

[To see links please register here]

Reply

#19
I know the question asked about "write" but in a more general sense "append" might be useful in some cases as it is easy to use in a loop to add text to a file (whether the file exists or not). Use a "\n" if you want to add lines eg:

const fs = require('fs');
for (var i=0; i<10; i++){
fs.appendFileSync("junk.csv", "Line:"+i+"\n");
}


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through