Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support running inside of a worker thread #37

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Atomically and asynchronously writes data to a file, replacing the file if it al
exists. data can be a string or a buffer.

The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`.
Note that `process.pid` is replaced by `require('worker_threads').threadId` if running inside of a worker thread.
If writeFile completes successfully then, if passed the **chown** option it will change
the ownership of the file. Finally it renames the file back to the filename you specified. If
it encounters errors at any of these steps it will attempt to unlink the temporary file and then
Expand Down
17 changes: 16 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,26 @@ var onExit = require('signal-exit')
var path = require('path')
var activeFiles = {}

// if we run inside of a worker_thread, `process.pid` is not unique
var id = (function getId () {
SimenB marked this conversation as resolved.
Show resolved Hide resolved
try {
var workerThreads = require('worker_threads')

if (workerThreads.isMainThread) {
return process.pid
}
SimenB marked this conversation as resolved.
Show resolved Hide resolved

return workerThreads.threadId || process.pid
} catch (e) {
return process.pid
}
})()

var invocations = 0
function getTmpname (filename) {
return filename + '.' +
MurmurHash3(__filename)
.hash(String(process.pid))
.hash(String(id))
.hash(String(++invocations))
.result()
}
Expand Down