1

Does node.js support writing random access?

I see this package, but it doesn't work (if I write two or more parts, the file is corrupt)

Or Smith
  • 3,556
  • 13
  • 42
  • 69
  • 1
    You mean like accessing data in a file after particular offset location ? – user568109 Jun 15 '14 at 13:38
  • @user568109: Yes, I have, for example. file it size is 1024 KB, and I get it in chunks of 256KB. So I want to write the first chunk in 0 offset. the second in offset 256, and so on. – Or Smith Jun 15 '14 at 13:40
  • sounds like streams would fit – vkurchatkin Jun 15 '14 at 15:16
  • Does this answer your question? [How do I do random access reads from (large) files using node.js?](https://stackoverflow.com/questions/13932967/how-do-i-do-random-access-reads-from-large-files-using-node-js) – Inigo Feb 15 '21 at 22:29

1 Answers1

5

fs core library should suffice for that. Here is the list of functions to use:

  1. fs.open(path, flags, [mode], callback)
  2. fs.write(fd, buffer, offset, length, position, callback)
  3. fs.writeSync(fd, buffer, offset, length, position)
  4. fs.read(fd, buffer, offset, length, position, callback)
  5. fs.readSync(fd, buffer, offset, length, position)

They are analogous to how you would do it in C.

user568109
  • 47,225
  • 17
  • 99
  • 123
  • @OrSmith Can you add the code to the question and tell what you are trying to do. I cannot understand the above code. – user568109 Jun 15 '14 at 14:38
  • No, it doesn't. when I upload 2 parts or more, I see that my file contains some source code of the middleware package. I use `app.configure(function () { app.use(express.bodyParser()); });`. It can be related? – Or Smith Jun 16 '14 at 07:07
  • @OrSmith bodyParser has been deprecated. If you use older version, I suggest you use a recent version. Otherwise the problem could be difficult to find/solve. – user568109 Jun 16 '14 at 07:48
  • Thanks, but I use the latest version: `4.4.3` – Or Smith Jun 16 '14 at 07:54