lostdorje
lostdorje

Reputation: 6470

node fs.writeFileSync() never returns

I'm creating a pipe and trying to write to it. But the writing never works.

import * as fs from 'fs';
import * as mkfifo from 'mkfifo';

mkfifo.mkfifoSync('/tmp/my_fifo', 0o600);

fs.writeFileSync('/tmp/my_fifo', 'Hey there!');

console.log('here');

If I comment everything except mkfifo.mkfifoSync('/tmp/my_fifo', 0o600); I see the pipe is created ok.

However, fs.writeFileSync('/tmp/my_fifo', 'Hey there!'); never returns.

Even when I use the callback version `fs.writeFile()1 the callback is never fired.

fs.writeFile('/tmp/my_fifo', 'Hey there!', (err) => {
    if (err) {
        return console.log('Write error: ' + err);
    }

    console.log('Write success');

    process.exit();
});

The callback is never called.

What am I doing wrong?

Just as a check I open up and tried to read the pipe from another script:

fs.readFile('/tmp/my_fifo', (err, data) => {
    if (err) {
        return console.log('Read error: ' + err);
    }

    console.log('Read success. Data is: ' + data);
});

On the writer side I see the error:

Error: ESPIPE: invalid seek, write

On the reader side I see:

Read success. Data is: 

empty data, but a successful read.

Update

If I don't create the pipe at all via mkfifoSync(), and instead just call fs.writeFileSync(), it will create and write to the file just fine.

So my question is how do I write to this pipe?

Upvotes: 2

Views: 2402

Answers (1)

0.sh
0.sh

Reputation: 2752

you have to use the appendFileSync method not the writeFileSync method for writing to a named pipe

append to named pipes

const fs = require("fs");
const mkfifo = require("mkfifo");

mkfifo.mkfifoSync("/tmp/my_fifo", 0o600);
fs.appendFileSync("/tmp/my_fifo", "hello world", ...);

read from named pipes

const fs = require("fs");
console.log(fs.readFileSync("/tmp/my_fifo").toString());

Upvotes: 1

Related Questions